For example I have the following test (JUnit 4.12, Mockito 1.9.5)
public class SomeServiceTest {
SomeDao someDao = mock(SomeDao.class);
SomeService someService = new SomeService(someDao);;
@Test
public void test() {
UserModel user = mock(UserModel.class);
when(user.getName()).thenReturn("name");
someService.perform(user);
verify(someDao).someDaoMethod(any(), eq(user.getName()));
}
}
It fails because mockito thinks that method someDaoMethod
was not called with value returned by user.getName()
.
But if I replace the last line with
String name = user.getName();
verify(someDao).someDaoMethod(any(), eq(name));
It passes! So if name == user.getName()
why then someDaoMethod(any(), eq(user.getName()))
fails but someDaoMethod(any(), eq(name))
passes? And is there any way to overcome this without creating local variables?
Bellow are implementations of SomeService
and SomeDao
. UserMode
is simply a JavaBean.
public class SomeService {
private SomeDao someDao;
public SomeService(SomeDao someDao) {
this.someDao = someDao;
}
public void perform(UserModel user) {
someDao.someDaoMethod("random", user.getName());
}
}
public class SomeDao {
public void someDaoMethod(String id, String name) {
//...
}
}