Mockito局部变量

时间:2017-10-30 16:45:41

标签: java spring mocking mockito

我正在使用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"));

2 个答案:

答案 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"的参数。