gpt4 book ai didi

unit-testing - Mono.doOnError() react 器 block 单元测试

转载 作者:行者123 更新时间:2023-12-05 00:58:56 27 4
gpt4 key购买 nike

我有一个使用 spring webflux 和 reactor 的休息 Controller ,我正在为 Controller 编写单元测试。请在下面找到代码片段并帮助我编写单元测试方法来测试 .doOnError block 。

我尝试使用 Mockito 引发异常

doThrow(CriticalException.class) .when(myService).myMethod(object);

This is my unit test


StepVerifier.create(
Mono.just(
webTestClient.post()
.uri("/endpoint")
.accept(MediaType.APPLICATION_JSON)


.body(BodyInserters.fromObject(requestJson)) //Set the body of the request to the given synchronous Object
//Returns:a Mono with the response
//Act
.exchange() //Perform the exchange
//Assert
.expectStatus().isOk()
.expectBody(Agreement.class)
.returnResult()
.getResponseBody()))
.expectNextMatches(agreementResponse -> {
assertNotNull(agreementResponse.getAgreementParticipant());
return true;
})
.expectComplete()
.verify();

这是我的 Controller

return Mono.fromCallable(() -> { 
myService.myMethod(object);
return object;
}).log().subscribeOn(Schedulers.elastic())
.map(p -> ResponseEntity.ok(p))
.defaultIfEmpty(ResponseEntity.notFound().build())
.doOnError(e -> {
LOGGER.error(LOG_FORMAT, e.getMessage(), e.getStackTrace());
});


Mockito is not returning exception while myService.myMethod(object) is been called.
Please suggest proper way to write test for .defaultIfEmpty and .doOnError blocks

最佳答案

而不是在模拟 myService.myMethod(object) 时抛出 CriticalException.class 返回一个 exception 包裹在 Mono

例如:

Mockito.doReturn(Mono.error(Exception::new)).when(service).callableMethod();

在下面找到示例代码片段

import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;

class Service {

public Mono<String> callableMethod() {

return Mono.just("1");
}
}

class Controller {

private Service service;

public Controller(Service service) {

this.service = service;
}

public Mono<String> endpoint() {

return service.callableMethod().doOnError(throwable -> {
System.out.println("throwable = " + throwable);
});
}
}

public class TestClass {

@Mock
private Service service = Mockito.mock(Service.class);

@Test
public void controllerTest() {

Mockito.doReturn(Mono.error(Exception::new)).when(service).callableMethod();

StepVerifier.create(new Controller(service).endpoint()).verifyError();
}
}

关于unit-testing - Mono.doOnError() react 器 block 单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55522755/

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