【问题标题】:StepVerifier::expectError accepts any exception in SpockStepVerifier::expectError 接受 Spock 中的任何异常
【发布时间】:2022-06-12 04:05:58
【问题描述】:

我正在测试一个使用 Spring Boot 的 webflux 库的类,我遇到了 StepVerifier::expectError 的奇怪行为。具体来说,我可以将 any 类型(甚至是 String!)传递给方法并且测试通过。对于这个特定的测试,我的被测方法应该以错误 Mono 响应,并且该 mono 应该包含一个自定义异常。我对this SO question 的理解是我的StepVerifier 在正确的块中运行。这里出了什么问题?

被测类:

@Service
@RequiredArgsConstructor
public class PaymentsBO {
    private final ContractClient contractClient;

    public Mono<Void> updatePaymentInfo(Request record) {
        return contractClient
                .getContract(UUID.fromString(record.getContractUuid()))
                .onErrorResume(throwable -> Mono.error(() -> new CustomException(
                        "Contract Service responded with a non-200 due to "
                                + throwable.getCause())))
                .flatMap(
                    // happy-path logic
                );
    }
}

单元测试:

def "Returns an error if the Contract Service returns a non-200"() {
    given:
    def testSubject = new PaymentsBO(contractServiceMock)
    def contractServiceMock = Mock(ContractClient)
    
    when:
    def result = testSubject.updatePaymentInfo(record)

    and:
    StepVerifier.create(result)
        .expectError(String.class)

    then:
    1 * contractServiceMock.getContract(CONTRACT_UUID) >> Mono.error(new ContractServiceException())
}

【问题讨论】:

    标签: groovy spring-webflux project-reactor spock reactive


    【解决方案1】:

    StepVerifier 文档中,我们可以读到必须通过调用verify 方法之一来触发验证

    使用 verify() 或 verify(Duration) 在其 Publisher 上触发生成的 StepVerifier 的验证。 (注意上面的一些终端期望有一个“验证”前缀的替代方案,既声明期望又触发验证)。 https://projectreactor.io/docs/test/release/api/reactor/test/StepVerifier.html

    您的代码没有使用verify 方法。

    请考虑以下两种情况:

        @Test
        void without_verify() {
            Mono.error(new IllegalArgumentException(""))
                    .as(StepVerifier::create)
                    .expectError(NullPointerException.class);
        }
        @Test
        void with_verify() {
            Mono.error(new IllegalArgumentException(""))
                    .as(StepVerifier::create)
                    .expectError(NullPointerException.class)
                    .verify();
        }
    

    without_verify 正在通过,因为没有触发验证。

    with_verify 失败,因为已触发验证。

    【讨论】:

    • 是的,我最终想通了,但感谢您的确认。有人建议使用verifyComplete,但这不是从expectError 链接的选项,所以我有点难过。
    猜你喜欢
    • 1970-01-01
    • 2022-08-13
    • 2014-05-10
    • 1970-01-01
    • 2013-12-24
    • 2021-09-24
    • 2013-06-27
    • 1970-01-01
    • 2016-07-11
    相关资源
    最近更新 更多