Mockito 单元测试:参数匹配器的使用无效

Mockito unit testing: Invalid use of argument matchers

我看到数十次相同的 Mockito 异常,但就我而言,我真的不明白我应该做什么,因为我没有混合匹配器和值。情况如下:

我有一个调用服务的 REST 资源,我想模拟该服务并将模拟的服务注入 REST 资源。这是代码:

  @Mock
  private Service service;
  @InjectMocks
  private Resource resource;
  ...
  @Test
  public void test() throws URISyntaxException
  {
    assertThat(resource).isNotNull();
    doNothing().when(service).createItem(anyLong(), any(Item.class));
    when(resource.createItem(any(Item.class))).thenReturn(Response.created(new URI("/items")).build());
    Response response = resource.createItem(item);
    Mockito.verify(service).createItem(item);
  }

例外情况:

-> at fr.simplex_software.micro_services_without_spring.customers.tests.TestCustomers.testCreateCustomer(TestCustomers.java:59)

This exception may occur if matchers are combined with raw values:
    //incorrect:
    someMethod(anyObject(), "raw String");
When using matchers, all arguments have to be provided by matchers.
For example:
    //correct:
    someMethod(anyObject(), eq("String by matcher"));

For more info see javadoc for Matchers class.

我不认为我在这里混合了匹配器和值。有人可以帮忙吗?

您正在尝试存根您的 class 待测 (Resource) 这不是模拟。

when(resource.createItem(any(Item.class))).thenReturn(Response.created(new URI("/items")).build());

在为您的 Resource class 编写单元测试时,不需要模拟这个 class 的任何内部结构,并且只需要模拟它的合作者。

  • @Mock 创建您的 class.
  • 的协作者 (Service) 的模拟
  • @InjectMocks 实例化您的 class 被测实例,同时向其注入所有模拟。

您不能存根测试的任何方法 class 因为您正在使用它的真实实例。