考虑以下代码:
public Mono<Void> doStuff() {
return this.requestStuff()
.onStatus(HttpStatus::is5xxServerError,
clientResponse -> {
aMethodIWouldLikeToTest(clientResponse);
return Mono.error(new MyCustomException("First error I would like to test"));
})
.onStatus(HttpStatus::is4xxClientError,
clientResponse -> {
aMethodIWouldLikeToTest(clientResponse);
return Mono.error(new MyCustomException("Second error I would like to test"));
})
.bodyToMono(String.class)
.flatMap(x -> anotherMethodIManagedToTest(x)))
}
我的首要目标是测试使用以下方法实现的 otherMethodIManagedToTest(x):
import org.springframework.web.reactive.function.client.WebClient;
...
@Mock
private WebClient.ResponseSpec responseSpec;
private String desiredInputParam = "There is another black spot on the sun today!";
...
@Test
public void allGood_anotherMethodIManagedToTest_success {
...
ClassUnderTest classUnderTest = new classUnderTest()
ClassUnderTest classUnderTestSpy = spy(classUnderTestSpy);
doReturn(responseSpec).when(classUnderTestSpy).requestStuff();
when(responseSpec.onStatus(any(), any())).thenReturn(responseSpec);
when(responseSpec.bodyToMono(String.class)).thenReturn(Mono.just(desiredInputParam));
Mono<Void> result = classUnderTestSpy.doStuff();
// Bunch of assertions for anotherMethodIManagedToTest(String desiredInputParam) performed with success ...
}
现在,我想创建其他测试来测试5xxServerError事件和4xxClientError事件,但是我很难确定如何做到:
关于如何执行这些操作的任何建议?
请注意,我不能真正使用任何PowerMock替代方法(如果这是实现我的目标的唯一途径,请继续关注),所有使用标准Mockito的答案都是首选。
答案 0 :(得分:0)
我认为我的问题的答案是 Mockito不是测试这种事情的正确工具。使用Wiremock似乎很方便
当我主要使用以下库进行测试时:
我设法完成了工作。
如果您遇到类似的问题,建议您看一下https://www.sudoinit5.com/post/spring-boot-testing-consumer/,所提供的示例与我为完成测试所做的类似。
但是,如果有人知道用Mockito解决问题的方法,我仍然很感兴趣。