2017-06-19 64 views
0

我试着为spock中的CompletableFuture创建存根或模拟。我的方法被称为异步并返回CompletableFuture。在spock方法中总是返回null。怎么了?Spock中的Mock CompletableFuture

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 
    } 
} 

更新代码,它没有完成。

+0

为什么不包含在这个问题你的代码,以便它更容易让我们看到什么正在进行 –

+0

' public void create(String name){ this.checkProductExists(name); } 公共CompletableFuture checkProductExists(字符串名称){// imeplementation }' 这样的事情。 – Matrix12

+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 
    } 
} 
+0

还是nullpointe rexception – Matrix12

+0

@ Matrix12请提供实际的可运行代码,我已经给出了我的答案,因为你的代码让我最好。 –

0

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

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 
 
    }