【问题标题】:Mocked class not called within Mono.map()Mono.map() 中未调用模拟类
【发布时间】:2021-03-10 22:42:16
【问题描述】:

我有一个 Spring Webflux 控制器,它将业务逻辑和映射委托给几个 @Service 类:

@RestController
@RequestMapping("/v1/transactions")
class TransactionController {

    @Autowired
    TransactionService service

    @Autowired
    TransactionMapper mapper

    Flux<Transaction> getTransactions(@PathVariable String id) {
        service.getTransactions(id)
               .map({ mapper.mapTransaction(it) })
    
    }
}

我的单元测试一直有效,直到它需要进入 map() 函数。我收到的调用太少了 1 * mockMapper.mapTransaction(_) >> Flux.just(new MappedTransaction())。

class TransactionControllerSpec extends Specification {
    def mockService = Mock(TransactionService)
    def mockMapper = Mock(TransactionMapper)

    def controller = new TransactionController(service: mockService, mapper: mockMapper)

    def "should call the transactions service to fetch a list of transactions"() {
        given: "an id"
        def id = "123"

        when: "the controller is called to fetch data"
        def result = controller.getTransactions(id)

        and: "code is executed"
        StepVerifier
            .create(result)
            .consumeNextWith({
               // some assertions here
            })

        then: "the service layer is called"
        1 * mockService.getTransactions(id) >> Flux.just(new Transaction())
        1 * mockMapper.mapTransaction(_) >> Flux.just(new MappedTransaction())
        // ???? Returns "Too few invocations (0 invocations)"
    }
}

我注意到,如果我在 Mono.map() 函数内设置断点,我的断点不会被命中。

【问题讨论】:

    标签: junit spring-webflux project-reactor spock


    【解决方案1】:

    好的,这对我来说是一个巨大的疏忽。但是,缺少的部分是我忘记告诉StepVerifier 来验证Flux 是否完整:

            and: "code is executed"
            StepVerifier
                .create(result)
                .consumeNextWith({
                   // some assertions here
                })
                .verifyComplete()
                // ? subscribes to the Mono/Flux
    

    【讨论】:

    • 真的解决了“调用太少”的问题吗? O_o
    • @Mr.Ustiik 确实如此——我在另一篇文章中了解到StepVerifier 属于when 块,因为它正在执行代码或消耗冷流。 then 块允许您使用 spock 执行基于交互的断言。
    猜你喜欢
    • 1970-01-01
    • 2019-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-07
    • 1970-01-01
    相关资源
    最近更新 更多