[英]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.我看到数十次出现同样的 Mockito 异常,但就我而言,我真的不明白我应该做什么,因为我不混合匹配器和值。 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.我有一个调用服务的 REST 资源,我想模拟该服务并将模拟的服务注入 REST 资源。 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.您正在尝试存根您的 class 正在测试( Resource
)不是模拟的。
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.在为您的Resource
class 编写单元测试时,不需要模拟此 class 的任何内部结构以及它的协作者。
@Mock
creates a mock of the collaborator ( Service
) of your class. @Mock
创建 class 的合作者 ( Service
) 的模拟。@InjectMocks
instantiates a real instance of your class under test while injecting all mocks to it. @InjectMocks
实例化您正在测试的 class 的真实实例,同时将所有模拟注入其中。You can't stub any methods of your tested class because you are working with a real instance of it.您不能存根测试过的 class 的任何方法,因为您正在使用它的真实实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.