Reputation: 135
I am using mockito with spring (java 1.8) and I am trying to use a local variable inside my Answer object:
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;
}
But I am getting this error:
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"));
Upvotes: 1
Views: 705
Reputation: 311373
The error has nothing to do with your Answer
. It's generated from this line:
Mockito.when(mockService.get(anyString(), ProductDTO.class))
.thenReturn((IBaseCouchbaseDTO) productForMock);
And, as the error explains "This exception may occur if matchers are combined with raw values". To solve this you need to use a Matcher
instead of the ProductDTO.class
value. eq
should fit the bill:
Mockito.when(mockService.get(anyString(), eq(ProductDTO.class)))
// Here --------------------------^
.thenReturn((IBaseCouchbaseDTO) productForMock);
Upvotes: 1
Reputation: 41223
The error This exception may occur if matchers are combined with raw values:
means:
You can have an expectation containing raw values:
Mockito.when(mockMixer.mix("red","white")).thenReturn("pink");
... or you can have an expectation containing matchers:
Mockito.when(mockMixer.mix(startsWith("re"), endsWith("ite")).thenReturn("pink"));
... but you can't have a mixture of both:
// Compiles, but will cause runtime exception
Mockito.when(mockMixer.mix(startsWith("re"), "white").thenReturn("pink"));
The fix is to replace the raw value with eq("white")
-- now you're passing a matcher that looks for parameters equal to "white"
.
Upvotes: 0