我最近开始使用Mockito 3+ Junit 5+Spring5,我正在写一些示例测试,以了解Mockito是如何工作的。我有一个关于内部调用的问题。所以,我有一个注入了一些DAO组件someObjectDAO的spring组件A。A类:
@Component("aClass")
public class A {
@Autowired
private ObjectDAO someObjectDAO;
public Long countRecords() {
ObjectSearchCriteria search = new ObjectSearchCriteria();
return someObjectDAO.count(search);
}
}我想测试A的countRecords方法。我模拟并注入了someObjectDAO,如下所示:
@ExtendWith(MockitoExtension.class)
@ContextConfiguration("contextConfFileSomewhere")
public class ATest {
@Mock
ObjectDAO someObjectDAOMock;
@InjectMocks
A aComponent;
@Test
void testCount() {
ObjectSearchCriteria search = Mockito.mock(ObjectSearchCriteria.class);
Mockito.when(someObjectDAOMock.count(search)).thenReturn(1L);
Assertion.assertEquals(1L, aComponent.countRecords());
}
}但这种方式是不正确的,实际上PotentialStubbingProblem是被抛出的。
org.mockito.exceptions.misusing.PotentialStubbingProblem:
Strict stubbing argument mismatch. Please check:
- this invocation of 'count' method:
someObjectDAO.count(
com.example.java.ObjectSearchCriteria@45cc6b13
);
-> at com.example.java.A.countRecords()
- has following stubbing(s) with different arguments:
1. someObjectDAOMock.count(
Mock for ObjectSearchCriteria, hashCode: 204078646
);
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).
For more information see javadoc for PotentialStubbingProblem class.如果我理解正确的话,异常表明我传递的对象与测试代码中使用的实际对象不同,对吗?
那么,我如何模拟一个使用局部变量作为参数的内部方法呢?
发布于 2019-11-08 17:40:09
您想要模拟对带有参数的ObjectDAO.count的调用。您应该使用参数匹配器,而不是将预期参数的实例作为参数进行传递:
Mockito.when(someObjectDAOMock.count(Mockito.any(ObjectSearchCriteria.class)))
.thenReturn(1L);编辑:你可能永远不会想要“模拟一个局部变量”。您的目标是在不知道实现细节的情况下测试被测系统(countRecords方法)。您所能做的就是模拟依赖关系。
https://stackoverflow.com/questions/58763824
复制相似问题