简体   繁体   中英

Mockito unit testing: Invalid use of argument matchers

I see dozens of occurrences of this same Mockito exception but, in my case, I really don't understand what am I suppose to do as I don't mix matchers and values. Here is the case:

I have a REST resource which invokes a service and I want to mock the service and to inject the mocked service into the REST resource. Here is the code:

  @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);
  }

And the exception:

-> 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.

I don't think that I'm mixing matchers and values here. Could anyone please help?

You are trying to stub your class under test ( Resource ) that is not a mock.

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

When writing a unit test for your Resource class there shouldn't be the need to mock any internals of this class and only its collaborators.

  • @Mock creates a mock of the collaborator ( Service ) of your class.
  • @InjectMocks instantiates a real instance of your class under test while injecting all mocks to it.

You can't stub any methods of your tested class because you are working with a real instance of it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM