【问题标题】:Unit testing retries with project reactor使用项目反应器重试单元测试
【发布时间】:2019-07-15 20:40:40
【问题描述】:
我有一段代码是这样的:
somePublisher
.subscribeOn(...)
.flatMap { x -> someFunctionThatReturnsMono(x) }
.retry(3)
.subscribe()
到目前为止,我已经设法使用 reactor-test 中的工具对快乐路径进行单元测试,例如 map {...} 中的代码是否被调用。
现在我想测试错误并重试。如何测试以确保在发生连续错误时最多调用 4 次 someFunctionThatReturnsMono(x)?
【问题讨论】:
标签:
unit-testing
project-reactor
【解决方案1】:
简单的方法是模拟函数并计算其调用次数:
def 'Test retry'(){
setup:
someBean = Mock(SomeBean)
def testMono = Mono.just(X)
.flatMap { x -> someBean.someFunctionThatReturnsMono(x) }
.retry(3)
.subscribeOn(Schedulers.elastic())
when:
StepVerifier.create(testMono).verifyError(IllegalArgumentException)
then:
4 * someBean.someFunctionThatReturnsMono(_ as X) >> Mono.error(new IllegalArgumentException())
}
另一种是模拟函数以返回 PublisherProbe 和计数探测订阅:
def 'Test retry'() {
when:
PublisherProbe probe = PublisherProbe.of(Mono.error(new IllegalArgumentException()))
someBean = Mock(SomeBean) {
someFunctionThatReturnsMono(_) >> probe
}
def testMono = Mono.just(X)
.flatMap { x -> someBean.someFunctionThatReturnsMono(x) }
.retry(3)
.subscribeOn(Schedulers.elastic())
then:
StepVerifier.create(testMono).verifyError(IllegalArgumentException)
probe.subscribeCount() == 4
}
【解决方案2】:
这是我为我的一个用例做的:
def "should retry failed action given number of times"() {
given:
def invocationCounter = new AtomicInteger(0)
when:
Mono<Void> mono = myService.doSth()
.doOnError { invocationCounter.incrementAndGet() }
then:
StepVerifier.create(mono)
.verifyErrorMatches { it == expectedError }
and:
invocationCounter.get() == 1 + retryNum
}