【问题标题】:Java mockito service test parameter negationJava mockito服务测试参数否定
【发布时间】:2017-03-24 10:25:45
【问题描述】:

我尝试使用 mockito 2.7.15 测试我的服务。

首先我试试这个:

when(customerDaoMock.find(AdditionalMatchers.not(id1))).thenReturn(null);

但是我得到了一个InvalidUseOfmatchersException.. 所以我搜索了这个问题并找到了这个stackoverflow question。 之后我的第二次尝试是:

when(customerDaoMock.find(AdditionalMatchers.not(Mockito.argThat‌(id1)))).thenReturn(null);

但是Mockito 类不再有方法argThat

所以我的问题是如何在 mockito 中使用 not 否定方法?

或者对于这个问题还有其他选择,或者更好的解决方案吗?

【问题讨论】:

  • 什么是“find”方法签名?
  • 来自接口:public Customer find(Long id);
  • 您需要这份声明thenReturn(null)吗?任何无条件调用 mock 都返回 null
  • 感谢您的建议! :)

标签: java unit-testing testing java-8 mockito


【解决方案1】:

这是 AdditionalMatchers javadoc 的一个示例:

//anything but not "ejb"
mock.someMethod(not(eq("ejb")));

这是工作示例:

public static class Tmp {
    public String f(Long a) {
        return a.toString();
    }
}

@Test
public void mockitoTest() {
    Tmp mock = Mockito.mock(Tmp.class);
    when(mock.f(AdditionalMatchers.not(Mockito.eq(5L)))).thenReturn("42");

    Assert.assertEquals("42", mock.f(4L));
    Assert.assertNull(mock.f(5L));
}

【讨论】:

  • 感谢您的回复!不幸的是, mockito 的 AdditionalMatchers 没有带有一个参数的 eq 方法。 (长)检查这个:“The method eq(double, double) in the type AdditionalMatchers is not applicable for the arguments (Long)
【解决方案2】:

也许没有静态导入会更容易理解:

Mockito.when(customerDaoMock.find(AdditionalMatchers.not(Mockito.eq(id1))))
    .thenReturn(null);

因此您可以将ArgumentMatchers#eq(long)AdditionalMatchers#not(long) 配对使用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-06
    相关资源
    最近更新 更多