首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用局部变量作为参数的模拟内部方法

使用局部变量作为参数的模拟内部方法
EN

Stack Overflow用户
提问于 2019-11-08 17:29:45
回答 1查看 642关注 0票数 1

我最近开始使用Mockito 3+ Junit 5+Spring5,我正在写一些示例测试,以了解Mockito是如何工作的。我有一个关于内部调用的问题。所以,我有一个注入了一些DAO组件someObjectDAO的spring组件AA类:

代码语言:javascript
复制
@Component("aClass")
public class A {
   @Autowired
   private ObjectDAO someObjectDAO;

   public Long countRecords() {
       ObjectSearchCriteria search = new ObjectSearchCriteria();
       return someObjectDAO.count(search);
   }
}

我想测试AcountRecords方法。我模拟并注入了someObjectDAO,如下所示:

代码语言:javascript
复制
@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是被抛出的。

代码语言:javascript
复制
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.

如果我理解正确的话,异常表明我传递的对象与测试代码中使用的实际对象不同,对吗?

那么,我如何模拟一个使用局部变量作为参数的内部方法呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-11-08 17:40:09

您想要模拟对带有参数的ObjectDAO.count的调用。您应该使用参数匹配器,而不是将预期参数的实例作为参数进行传递:

代码语言:javascript
复制
 Mockito.when(someObjectDAOMock.count(Mockito.any(ObjectSearchCriteria.class)))
    .thenReturn(1L);

编辑:你可能永远不会想要“模拟一个局部变量”。您的目标是在不知道实现细节的情况下测试被测系统(countRecords方法)。您所能做的就是模拟依赖关系。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58763824

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档