【问题标题】:Mokito JUnit Test is failing when testing with 2 mocked dependencies with one relies on the other?使用 2 个模拟依赖项进行测试时,Mockito JUnit 测试失败,其中一个依赖于另一个?
【发布时间】:2020-11-20 22:44:30
【问题描述】:
Class ToBeTested{

@Autowired
private Repo1Src repo1;// JPA repository

@Autowired
private Repo2Src repo2;// JPA repository

 public Map<String, Object> getAll( long id) {
        List<Repo1Res> repo1Res= repo1.findAll(id);

        List<String> systems = new ArrayList<>(repo1Res.size());
        Map<String, SysSceDto> resultMap= getCorrespondanceSystemSytemDot(repo1Res);

        systems.addAll(resultMap.keySet());
        List<RepoRes2> repo2Res= repo2.findAll(systems,
                id,
                1L);
return new HashMap();
}
}
@RunWith(MockitoJUnitRunner.class)
class ToBeTestedTests{
@Mock
private Repo1Src repo1;

@Mock
private Repo2Src repo2;

@InjectMocks
private ToBeTested toBeTested;

@Test
public void test(){
 List<Repo1Res> lst1= new ArrayList<>();
 List<Repo2Res> lst2= new ArrayList<>();
 List<String> systems = new ArrayList<>();
 generate(lst1, lst2, systems );

 when(repo1.findAll(1)).thenReturn(lst1);
 when(repo2.findAll(systems , 1, 1L)).thenReturn(lst2);
 toBeTested.getAll(1);
}
}

我有以下异常: org.mockito.exceptions.misusing.UnnecessaryStubbingException 当我尝试运行测试时,这是我调用 when(repo2.findAll(systems , 1, 1L)).thenReturn(lst2 );

堆栈跟踪:

org.mockito.exceptions.misusing.UnnecessaryStubbingException: 

Unnecessary stubbings detected in test class: ToBeTestedTests
Clean & maintainable test code requires zero unnecessary code.
Following stubbings are unnecessary (click to navigate to relevant line of code):
  1. -> at ToBeTestedTests.test(ToBeTestedTests.java:22)
Please remove unnecessary stubbings or use 'lenient' strictness. More info: javadoc for UnnecessaryStubbingException class.

【问题讨论】:

  • 需要在这里上传更清晰的代码和堆栈跟踪结果吗?我的意思是为什么生成(lst1,lst2,系统)?
  • generate(lst1, lst2, systems ) 只是初始化 lst1, lst2, 系统变量它是一个简单的 list.add 函数
  • 我添加了额外的细节

标签: java spring-boot mocking mockito


【解决方案1】:

您的测试失败,因为在测试期间未调用您的第二个存储库 repo2 的存根。

似乎是存根设置

when(repo2.findAll(systems , 1, 1L)).thenReturn(lst2);

不完全反映测试执行期间调用repo2.findAll() 的参数。我假设它是 systems 变量。

作为第一个修复,您可以打开您的存根并接受任何列表:

when(repo2.findAll(anyList(), ArgumentMatchers.eq(1), ArgumentMatchers.eq(1L))).thenReturn(lst2);

...然后调试或打印systems 变量以了解差异在哪里。

然而,失败也或多或少是来自 Mockito 的 警告,因为您正在对未使用的方法进行存根。在最新版本的 Mockito 中,这变得更加严格,只要您存根测试期间未使用的内容,您的测试就会失败。

您可以将默认的STRICTNESS 覆盖为LENIENT(又名。我不在乎)或WARN 至少有警告输出但没有失败的测试:

@MockitoSettings(strictness = Strictness.LENIENT)

【讨论】:

    猜你喜欢
    • 2022-06-29
    • 2018-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-28
    相关资源
    最近更新 更多