模拟CompletableFuture in spock

时间:2017-06-19 17:03:05

标签: java spock

我在spock中尝试为CompletableFuture创建存根或模拟。我的方法称为async并返回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
    }
}

更新代码,它没有完成。

2 个答案:

答案 0 :(得分:0)

  • items.checkProductExists("Fake string") >> future:商品未定义,您的意思是factory
  • boolean result = this.repository.checkProductExists(name);这条线不会期待未来,所以你为什么要回来呢?
  • future.get() >> true您创建了一个真正的CompletableFuture,因此无法进行存根
  • 所有存根应在when / given块中的setup块之外执行
  • 您的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
    }
}

答案 1 :(得分:0)

您可以使用future.complete(true)

强制完成未来

&#13;
&#13;
select employee_id, name, in_time* 1.0/ total as ratio
from (
    select 
        employee_id,
        count(*) filter (where arrival >= time '8:30' - interval '5 minutes' and arrival <= time '8:30' + interval '5 minutes') as in_time,
        count(*) as total
    from stats
    where day in ('midweek', 'friday')
    group by 1
    ) s
join employee e on e.id = s.employee_id
where in_time* 1.0/ total >= 0.6;

 employee_id | name  |         ratio          
-------------+-------+------------------------
           1 | John  | 0.75000000000000000000
           2 | Susan | 0.75000000000000000000
(2 rows)    
&#13;
&#13;
&#13;