gpt4 book ai didi

java - Mockito 局部变量

转载 作者:行者123 更新时间:2023-11-30 06:26:51 28 4
gpt4 key购买 nike

我正在将mockito与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"));

最佳答案

该错误与您的答案无关。它是从这一行生成的:

Mockito.when(mockService.get(anyString(), ProductDTO.class))
.thenReturn((IBaseCouchbaseDTO) productForMock);

并且,正如错误所解释的“如果匹配器与原始值组合,则可能会发生此异常”。要解决此问题,您需要使用 Matcher 而不是 ProductDTO.class 值。 eq应该符合要求:

Mockito.when(mockService.get(anyString(), eq(ProductDTO.class)))
// Here --------------------------^
.thenReturn((IBaseCouchbaseDTO) productForMock);

关于java - Mockito 局部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47020322/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com