2017-09-13 96 views
2

我有一個類A作爲guice依賴。該集是單身人士。下面是代碼示例:Google Guice:模擬一個@provides方法由一組對象組成

class A 
{ 
    private Set<InetAddress> set; 
    private String pingUriPath; 
    @Inject 
    public A(Set<InetAddress> set, @Named("pingUri") String pingUriPath) 
     { 
      this.set = set; 
      this.pingUriPath = pingUriPath; // this is used somewhere 
     } 

    public void storeValue(String str) 
    { 
     if(str.equals("abc")) 
     { 
      set.add(str); 
     } 
    } 

} 

這裏是一個依賴注入的吉斯模塊:

private class GuiceModule extends AbstractModule { 
     @Override 
     public void configure() { 
      bindConstant().annotatedWith(Names.named("pingUri")).to("/ping"); 
     } 

     @Provides 
     @Singleton 
     Set<InetAddress> healthyTargets(){ 
      return Sets.newConcurrentHashSet(); 
     } 
    } 

我想嘲笑方法storeValue爲此,我不得不嘲笑集。我無法用guice來嘲笑這套遊戲。 如果我嘲笑像下面,它給斷言錯誤(這個模擬沒有相互作用)

@Mock 
Set<InetAddress> mockHealthyTargets; 

private class MockClassesModule extends AbstractModule { 
     @Override 
     public void configure() { 
      bindConstant().annotatedWith(Names.named("pingUri")).to("/ping"); 
     } 

     @Provides 
     @Singleton 
     Set<InetAddress> healthyTargets(){ 
      return Sets.newConcurrentHashSet(); 
     } 
    } 

public test_storeValue() 
{ 
    Injector injector = Guice.createInjector(new MockClassesModule()); 
    A a = injector.getInstance(A.class); 
    a.storeValue("abc"); 
    verify(mockHealthyTargets).add("abc") 
} 

回答

1

如果您有需要在單元測試中使用的吉斯,什麼是最有可能走錯方向。依賴注入的最大好處之一是測試變得簡單,因爲你可以傳遞由你控制的依賴。

我假設你想測試類A,特別是方法storeValue。爲此,你甚至不需要嘲笑

@Test 
public void test() { 
    // prepare dependencies 
    Set<InetAddress> set = Sets.newConcurrentHashSet(); 
    String pingUri = "example.com"; 

    // prepare input 
    String input = "someValue"; 

    // prepare class under test 
    A classUnderTest = new A(set, pingUri); 

    // call class under test 
    classUnderTest.storeValue(input); 

    // check that what you expected happened 
    // in this case you expect that the dependency set now contains the input 
    assertThat(set, contains(input)); 
} 
+0

在您的**單元中使用DI框架**測試表明某些事情發生了錯誤的方向。在你的**整合**測試中使用DI框架似乎對我來說好像 – Pelocho

+0

@Pelocho好點!我已經將它改爲單元測試 –

0

我發現錯誤是什麼,我應該返回模擬時提供給我的單元測試。它應該看起來像這樣:

@Mock 
Set<InetAddress> mockHealthyTargets; 

private class MockClassesModule extends AbstractModule { 
     @Override 
     public void configure() { 
      bindConstant().annotatedWith(Names.named("pingUri")).to("/ping"); 
     } 

     @Provides 
     @Singleton 
     Set<InetAddress> healthyTargets(){ 
      return mockHealthyTargets; 
     } 
    }