【问题标题】:Returning mock objects with Mockito using given arguments使用给定参数返回带有 Mockito 的模拟对象
【发布时间】:2020-01-31 11:35:02
【问题描述】:

对于我使用 Mockito 进行的 JUnit 测试,我正在执行以下操作:

    Mockito.lenient().when(tokenService.create(String id, Any)).thenReturn(new String (id))

    Mockito.lenient().when(voucherRepo.findById(id String).thenReturn(new Voucher(id));

我想访问给 tokenService.create() 和凭证Repo.findById() 方法的字符串 id,使用它创建然后返回模拟对象。怎么做?

【问题讨论】:

    标签: mockito junit4 junit5


    【解决方案1】:
    Mockito.when(voucherRepo.findById(id)).thenReturn(new Voucher(id));
    

    您的解决方案应该有效,并且可能是任何明确定义的测试的首选解决方案。 正如您在测试中知道的确切 id 是什么,您可以返回它的特定对象。

    另一种方法 - 对于任意字符串 - 使用 mockito 的 thenAnswer 功能:

    Mockito.when(voucherRepo.findById(Mockito.any(String.class))).thenAnswer(new Answer<Voucher>() {
    
        @Override
        public Voucher answer(InvocationOnMock invocation) throws Throwable {
    
            Object[] args = invocation.getArguments();
            String id = (String) args[0];
            return new Voucher(id);
        }
    });
    

    我不确定您在测试中必须这样做的原因是什么(因为这是一个相当随意的定义),但可以考虑为您的问题添加更多上下文。

    【讨论】:

      猜你喜欢
      • 2016-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-23
      • 1970-01-01
      • 1970-01-01
      • 2013-12-12
      • 1970-01-01
      相关资源
      最近更新 更多