因此,我有几个使用模仿程序运行的测试。一个需要模拟的静态对象,所以我像这样使用PowerMockito ...
BDDMockito.given(WebClient.create(any())).willReturn(webClientMock);
接下来,我还有另一个测试可以模拟这样的最终课程……
HttpSecurity security = Mockito.mock(HttpSecurity.class);
第二个一开始不起作用,出现以下故障....
Cannot mock/spy class org.springframework.security.config.annotation.web.builders.HttpSecurity
Mockito cannot mock/spy because :
- final class
因此,我查看并发现了this question,它建议将文件.../src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker
与mock-maker-inline
但是当我添加第一行失败时...
org.mockito.exceptions.misusing.NotAMockException:参数应该是模拟的,但是是:类java.lang.Class
我如何同时工作?
更新
我不想在整个测试中弄乱问题,这实际上并没有提供任何额外的上下文。但是,由于人们坚持并似乎误解了这个问题...
// Static
@ExtendWith(MockitoExtension.class)
@RunWith(PowerMockRunner.class)
@PrepareForTest(WebClient.class)
public class RasaServiceTest {
@Mock
private WebClient webClientMock;
@Mock
private WebClient.RequestHeadersSpec requestHeadersMock;
@Mock
private WebClient.RequestHeadersUriSpec requestHeadersUriMock;
@Mock
private WebClient.RequestBodyUriSpec requestBodyUriMock;
@Mock
private WebClient.ResponseSpec responseMock;
private MyService service = new MyService();
@BeforeAll
public void setup(){
PowerMockito.mockStatic(WebClient.class);
BDDMockito.given(WebClient.create(any())).willReturn(webClientMock);
}
@Test
public void HappyPath(){
MessageResponseItem item = new MessageResponseItem();
item.setRecipientId("id");
item.setResponseText("response");
MessageResponseItem[] items = {item};
when(webClientMock.post()).thenReturn(requestBodyUriMock);
when(requestHeadersUriMock.uri("/webhooks/rest/webhook")).thenReturn(requestHeadersMock);
when(requestHeadersMock.retrieve()).thenReturn(responseMock);
when(responseMock.bodyToMono(MessageResponseItem[].class)).thenReturn(Mono.just(items));
InferenceEngineRequest request = new InferenceEngineRequest();
MessageResponseItem[] result = service.call(request).block();
assertThat(result.length).isEqualTo(1);
assertThat(result[0].getResponseText()).isEqualTo("response");
}
}
// Final
@RunWith(MockitoJUnitRunner.class)
public class RemoveMeConfigTest {
@Test
public void happyPath() throws Exception {
HttpSecurity security = Mockito.mock(HttpSecurity.class);
CsrfConfigurer<HttpSecurity> csrf = Mockito.mock(CsrfConfigurer.class);
RemoveMeConfig config = new RemoveMeConfig();
Mockito.when(
security.csrf()
).thenReturn(csrf);
Mockito.when(
csrf.disable()
).thenReturn(security);
config.configure(security);
Mockito.verify(
security,
Mockito.times(
1
)
).csrf();
Mockito.verify(
csrf,
Mockito.times(1)
).disable();
}
}