Claudiu Matei
Claudiu Matei

Reputation: 4101

Testing expected method with EasyMock gets IllegalStateException

I am trying to test the service class to see if it calls the right method of the repository. The repository simply extends from CouchDbRepositorySupport

ServiceTest

@RunWith(EasyMockRunner.class)
@SpringApplicationConfiguration(App.class)
public class ServiceTest {

    @Rule
    public EasyMockRule mocks = new EasyMockRule(this);

    @TestSubject
    UserService userService = new UserServiceImpl();

    @Mock
    UserRepository userRepositoryMock;

@Test
    public void testGetUser() {
        User user = new User("Bob","bob87);

        user.setId("bob87"); //username is the id

        userService.getUser(user.getId());

        EasyMock.expect(userRepositoryMock.get(user.getId())).andReturn(user); //the line where the error occurs

        EasyMock.expectLastCall().times(1);

        EasyMock.replay(userRepositoryMock);

        EasyMock.verify(userRepositoryMock);
    }
}

However I get an IllegalStateException

java.lang.IllegalStateException: missing behavior definition for the preceding method call: CompanyRepository.get("Optis") Usage is: expect(a.foo()).andXXX()

Upvotes: 1

Views: 3708

Answers (1)

JB Nizet
JB Nizet

Reputation: 691765

You need to tell your mock what to do and call replay() before calling the service that calls this mock:

public void testGetUser() {
    User user = new User("Bob","bob87);
    user.setId("bob87"); //username is the id

    EasyMock.expect(userRepositoryMock.get(user.getId()))
            .andReturn(user); 
    EasyMock.expectLastCall().times(1);
    EasyMock.replay(userRepositoryMock);

    userService.getUser(user.getId());

    EasyMock.verify(userRepositoryMock);
}

Upvotes: 2

Related Questions