2017-09-13 11 views
2

私はクラスを持っており、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); 
     } 
    } 

} 

は、依存関係を注入Guiceのモジュールです:

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を使用してセットを模擬することができません。私は以下のように模擬した場合 、それはあなたがあなたのユニットテストで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

は、何かが最も可能性の高い間違った方向に行くされていないアサーションエラーが発生します。依存性注入の最大の利点の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フレームワークを使用すると、私にとってはOKと思われます – 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; 
     } 
    } 
関連する問題