我有一些使用CompletableFutures的异步调用,我的单元测试失败了。大多数情况下,他们没有失败,但有时他们可能会失败…。我收到的错误消息是:
org.mockito.exceptions.misusing.PotentialStubbingProblem:
Strict stubbing argument mismatch. Please check:
- this invocation of 'queryForList' method:
namedParameterJdbcTemplate.queryForList(
null,
MapSqlParameterSource {id=0},
class java.lang.String
);
...
Typically, stubbing argument mismatch indicates user mistake when writing tests.
Mockito fails early so that you can debug potential problem easily.
However, there are legit scenarios when this exception generates false negative signal:
- stubbing the same method multiple times using 'given().will()' or 'when().then()' API
Please use 'will().given()' or 'doReturn().when()' API for stubbing.
- stubbed method is intentionally invoked with different arguments by code under test
Please use default or 'silent' JUnit Rule (equivalent of Strictness.LENIENT).我尝试过使用doReturn().when(),但它仍然给出了相同的错误。使用Mockito.lenient()修复了它,但我认为使用Mockito.verify()方法是解决这个顽固性/异步问题的正确方法。
在添加验证和要返回的模拟之后:
Mockito.verify(namedParameterJdbcTemplate, Mockito.timeout(100).times(1)).queryForList(Mockito.anyString(), Mockito.any(MapSqlParameterSource.class), Mockito.eq(String.class));
Mockito.verify(namedParameterJdbcTemplate, Mockito.timeout(100).times(1)).query(Mockito.anyString(), Mockito.any(MapSqlParameterSource.class), Mockito.any(BasicMapper.class));
Mockito.when(namedParameterJdbcTemplate.queryForList(Mockito.anyString(), Mockito.any(MapSqlParameterSource.class), Mockito.eq(String.class))).thenReturn(null);
Mockito.when(namedParameterJdbcTemplate.query(Mockito.anyString(), Mockito.any(MapSqlParameterSource.class), Mockito.any(BasicMapper.class))).thenReturn(offerEvents);我犯了这个错误
Wanted but not invoked:
namedParameterJdbcTemplate.queryForList
...
Actually, there were zero interactions with this mock.我能解决这个问题的最好方法是什么?
发布于 2022-09-08 09:26:36
您没有显示完整的测试代码,但是您可能会将verify放在测试代码之前。移动它,使它在您正在测试的代码之后。
when用于设置模拟,因此必须在调用模拟以获取数据的代码之前调用它。
verify检查一个方法是否按预期在模拟上被调用,所以必须在调用模拟的代码之后调用它,否则什么都没有发生,验证就会失败。
顺便说一句,如果您的代码也验证了依赖于模拟提供的数据的结果,那么也没有必要在模拟上执行验证:根据用when完成的设置获得预期数据的事实应该足以确认模拟被调用了。
https://stackoverflow.com/questions/73644750
复制相似问题