gpt4 book ai didi

java - Spock测试中未返回 stub 对象方法值

转载 作者:行者123 更新时间:2023-12-03 10:07:14 24 4
gpt4 key购买 nike

我是Spock框架的新手,并编写了一个测试用例,其中我试图模拟一个名为QueryDatabase的类

public class QueryDatabase {

public BigInteger countRecords(Instant start, Instant end) {

Flux<CountRecord> countValue = query("select * from users");
Optional<Object> value = Optional.ofNullable(countValue.blockFirst()).map(CountRecord::getValue);
BigInteger count = value.filter(BigInteger.class::isInstance)
.map(BigInteger.class::cast).orElse(BigInteger.valueOf(0));

return count
}

public Flux<CountRecord> query(String query) {

}
}
但是下面的用于检查countRecords(Instant,Instant)返回的值的测试用例始终为0,这意味着部分时在 中返回的值
recordCount.query(_) >> Flux.just(CountRecord.builder().value(new BigInteger(133)).build())
没有被使用,似乎recordCount.query(_) >> Flux.empty()也没有任何影响,它总是返回默认的BigInteger值0
def "record count"() {

given:
def now = Instant.now()
def last10Minutes = now.minus(10, ChronoUnit.MINUTES);
def recordCount = Stub(QueryDatabase)

when: "query returning empty flux"
recordCount.query(_) >> Flux.empty()

then:
recordCount.countRecords(last10Minutes, now) == 0

when: "query returning the count record"
recordCount.query(_) >> Flux.just(CountRecord.builder().value(new BigInteger(133)).build())

then:
recordCount.countRecords(last10Minutes, now) == 133

}
我在这里做错什么吗?

最佳答案

您的代码有几个问题。

  • 您尝试在when
  • 中设置一些 stub
  • 您可以在then
  • 中执行操作
  • 您尝试重新定义 stub

  • 请参阅 Combining Mocking and Stubbing,了解其工作原理。
    def "record count"() {    
    given:
    def now = Instant.now()
    def last10Minutes = now.minus(10, ChronoUnit.MINUTES);
    def recordCount = Spy(QueryDatabase)

    when: "query returning empty flux"
    def result = recordCount.countRecords(last10Minutes, now)

    then:
    1 * recordCount.query(_) >> Flux.empty()
    result == 0

    when: "query returning the count record"
    def 2ndResult = recordCount.countRecords(last10Minutes, now) == 133

    then:
    1 * recordCount.query(_) >> Flux.just(CountRecord.builder().value(new BigInteger(133)).build())
    2ndResult == 133
    }
    或者,您可以将其拆分为数据驱动功能
    def "record count"(BigInteger result, Flux input) {    
    given:
    def now = Instant.now()
    def last10Minutes = now.minus(10, ChronoUnit.MINUTES);
    def recordCount = Spy(QueryDatabase)
    recordCount.query(_) >> input

    expect:
    recordCount.countRecords(last10Minutes, now) == result

    where:
    result | input
    0 | Flux.empty()
    133 | Flux.just(CountRecord.builder().value(new BigInteger(133)).build())
    }
    通常,您会以相反的方式对参数进行排序,但是由于通量是如此冗长,因此我发现它的可读性更好。
    -
    编辑:
    我错过了您尝试对正在测试的对象进行 stub 的操作,这只能通过 partial mocking来完成,并且经常指示应重构代码。因此,将 Mock/ Stub替换为 Spy进行部分模拟。

    关于java - Spock测试中未返回 stub 对象方法值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65736315/

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