我有一個類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")
}
在您的**單元中使用DI框架**測試表明某些事情發生了錯誤的方向。在你的**整合**測試中使用DI框架似乎對我來說好像 – Pelocho
@Pelocho好點!我已經將它改爲單元測試 –