2017-06-19 65 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 
 
    }