繁体   English   中英

在Spock中模拟CompletableFuture

[英]Mock CompletableFuture in spock

我试图在Spock中为CompletableFuture创建存根或模拟。 我的方法称为异步并返回CompletableFuture。 在spock方法中,始终返回null。 怎么了?

public class  ProductFactory() {

    @Autowired
    ProductRepository repository;

    public Product create(String name) { 
        this.checkProductExists(name);
    }


    public CompletableFuture<Boolean> checkProductExists(String name) {
        //call repository and return 
        boolean  result = this.repository.checkProductExists(name);

        return CompletableFuture.completedFuture(result)
    }
}





class ProductFactorySpec extends Specification {


    ProductRepository repository = Mock(ProductRepository)


    ProductFactory factory = new ProductFactory(repository)

    def "When i decide create new product"() {

        def future = CompletableFuture.completedFuture(true)

        when:

        repository.checkProductExists("Fake string") >> future

        future.get() >> true

        def result = this.factory.create(fakeOfferData())
        then:
        result instanceof Product
    }
}

更新代码,尚未完成。

  • items.checkProductExists("Fake string") >> future :未定义项目,您的意思是factory吗?
  • boolean result = this.repository.checkProductExists(name); 这条线不希望有未来,所以为什么要尝试返回
  • future.get() >> true您创建了一个真实的CompletableFuture因此无法进行存根
  • 所有存根都应在given / setup块中的when块之外执行
  • 您的create未返回Product

从您提供的代码中:

class ProductFactorySpec extends Specification {


    ProductRepository repository = Stub()


    ProductFactory factory = new ProductFactory(repository)

    def "When i decide create new product"() {
        given:
        repository.checkProductExists(_) >> true

        when:
        def result = factory.create("fakeProduct")

        then:
        result instanceof Product
    }
}

您可以使用future.complete(true)强制完成未来。

 def "When i decide create new product"() { def future = new CompletableFuture<Boolean>() when: repository.checkProductExists("Fake string") >> future future.complete(true) def result = this.factory.create(fakeOfferData()) then: result instanceof Product } 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM