Reputation: 537
I am using Junit4 and Mockito to test some logic.
After I run the test method, the result is returning an empty list of an object while I have mocked objects and add to the list. It should have one object in the result list.
I have tried to debug the test and still see that the result list does not contain any object. The following code is just to simulate the real code that I have but they are basically the same idea.
This is the method that I want to test: a new list is created inside the method and then there are some filter going on to add items in the list and then return the result.
public List<TemplateDto> getTemplates(String name) {
List<TemplateDto> result = new ArrayList<>();
result.addAll(
template.getTemplates().stream().filter(t -> t.getName().equals(name))
.map(s -> new TemplateDto(s.getId(),s.getName()))
.collect(Collectors.toList())
);
return result;
}
This is the test method logic. I mocked one object, expecting the result to return the same object
@Test
public void getTemplates() {
classToTest = mock(ClassToTest.class);
Template template1 = new Template(1,"template1");
List<Template> templates = new ArrayList<>();
templates.add(template1);
template = mock(Template.class);
when(template.getTemplates()).thenReturn(templates);
List<TemplateDto> result = classToTest.getTemplates("template1");
assertEquals(result.get(0).getName(),"template1");
}
The test should pass but instead, it fails with the following error:
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
Is there anything else that I need to mock to get the expected result?
Upvotes: 3
Views: 4199
Reputation: 26532
1) You never mock class under test
2) You have to set the mocked value on the class under test
classToTest = new ClassToTest();
template = mock(Template.class);
classToTest.setTemplate(template);
when(template.getTemplates()).thenReturn(templates);
List<TemplateDto> result = classToTest.getTemplates("template1");
Upvotes: 6