我正在使用mock与spring(java 1.8),我试图在我的Answer对象中使用一个局部变量:
public IProductDTO productForMock = null;
@Bean
@Primary
public ICouchbaseDTOProvider mockCreateProductDelegate() {
CouchbaseDTOProvider mockService = mock(CouchbaseDTOProvider.class);
Mockito.when(mockService.get(anyString(), ProductDTO.class)).thenReturn((IBaseCouchbaseDTO) productForMock);
Mockito.when(mockService.getEnvironment()).thenReturn(null);
Mockito.when(mockService.insert((IBaseCouchbaseDTO) anyObject())).thenAnswer(
new Answer<IProductDTO>() {
@Override
public IProductDTO answer(InvocationOnMock invocation) throws Throwable {
productForMock = invocation.getArgumentAt(0, IProductDTO.class);
return null;
}
}
);
return mockService;
}
但是我收到了这个错误:
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"));
答案 0 :(得分:1)
该错误与您的Answer
无关。它来自这一行:
Mockito.when(mockService.get(anyString(), ProductDTO.class))
.thenReturn((IBaseCouchbaseDTO) productForMock);
并且,正如错误解释&#34;如果匹配器与原始值结合可能会发生此异常&#34;。要解决此问题,您需要使用Matcher
而不是ProductDTO.class
值。 eq
符合条例草案:
Mockito.when(mockService.get(anyString(), eq(ProductDTO.class)))
// Here --------------------------^
.thenReturn((IBaseCouchbaseDTO) productForMock);
答案 1 :(得分:0)
错误This exception may occur if matchers are combined with raw values:
表示:
您可以期望包含原始值:
Mockito.when(mockMixer.mix("red","white")).thenReturn("pink");
...或者您可以期待包含匹配器:
Mockito.when(mockMixer.mix(startsWith("re"), endsWith("ite")).thenReturn("pink"));
...但你不能混合使用两者:
// Compiles, but will cause runtime exception
Mockito.when(mockMixer.mix(startsWith("re"), "white").thenReturn("pink"));
修复方法是将原始值替换为eq("white")
- 现在您正在通过匹配器查找等于"white"
的参数。