私はクラスを持っており、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")
}
あなたの**ユニット**テストでDIフレームワークを使用して、何かが間違った方向に行っていることを示しています。 **統合**テストでDIフレームワークを使用すると、私にとってはOKと思われます – Pelocho
@Pelocho良い点!私はユニットテストに変更しました –