java - Junit test list returns null even when objects inside the list have been mocked
问题描述
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?
解决方案
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");
推荐阅读
- python - 有没有办法从这样的字符串中获取选择性数据?
- macos - 我的 ZSH 完成在开始时不起作用,但在我获取 .zshrc (Mac) 时它们会起作用
- javascript - 如何将cshtml文件的脚本标签中的变量传递给另一个javascript文件?
- angular - 如何从角度 11 中的 http 登录响应中获取 cookie?
- symfony - Symfony:Twig 中的多个“for”循环
- git - 删除一些提交,但保留更改
- python-3.x - 如何分离图形的图像?
- javascript - 轻量级图表不显示 y 轴
- firebase - 如何将电话号码链接到已经登录的firebase gmail用户
- javascript - Node js - 页面渲染发生在数据库更新之前