I am failing to write a Test because the answer of my when().thanReturn() is not returning anything. I am not able to mock the behavior (Setup is Spring Boot, Java 8, Junit 4). The problem is that the Method being called is taking method References as a parameters:
List<PubSubMessage> findMessages(DateCheckerPredicate whichDateFunction, MessageRepoPredicate whichQueryToUse, int tableId) {
List<PubSubMessage> rulesToPublish = new ArrayList<>();
List<Object> queryResult = whichQueryToUse.findObjects(tableName);
if(queryResult != null) {
queryResult.forEach(object -> {
if(whichDateFunction.checkDates(object)) {
rulesToPublish.add(new PubSubMessage(tableId, object.getId()));
}
});
}
return rulesToPublish;
}
Calling the method looks something like this:
public void methodToTest {
List<PubSubMessage> messages = dao.findMessages(MessageDateChecker::msgCanBePublished, msgRepo::findMsgesToPublish, tableId);
}
where MessageDateChecker uses static "helper Methods" and msgRepo is a class which is annotated with Springs @Service and using jdbcTemplates to query the DB. And the class looks something like this:
private Dao dao;
private MsgRepo msgRepo;
@Autowired
public SomeService(Dao dao, MsgRepo msgRepo) {
this.dao = dao;
this.msgRepo = msgRepo;
}
The test setup looks something like this:
@Mock
private Dao dao;
@Mock
private MsgRepo msgRepo;
@InjectMock
public SomeService(dao, msgRepo)
private int tableId = 1;
private String tableName = "someTableName";
@Test
public void someTest() {
List<PubSubMessage> list = new ArrayList<>();
list.add(new PubSubMessage(tableId, 12));
List<Object> objects = new ArrayList<>();
objects.add(new Object(12, new Date(), null));
when(dao.findMessages(MessageDateChecker::msgCanBePublished, msgRepo::findMessagesToActivate, tableId)).thenReturn(list);
someService.methodToTest() //in here findRules is getting called()
verify(someClass,times(1)).someMethod()
}
Like I mentioned above the when().thanReturn() should return the predefined list but when running the test, it always returns null. Does anyone can provide some help? Probably I need to do a better job mocking the method-references which are being passed at a parameter. But So far I am failing to do it right.