我有一个 A 类,它将一个集合作为 guice 依赖项。该集合是单例的。下面是代码示例:
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);
}
}
}
这里是注入(inject)依赖的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 模拟集合。 如果我像下面这样模拟,它会给出断言错误(与这个模拟没有交互)
@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")
}
最佳答案
如果您需要在单元测试中使用 guice,那么很可能是方向错误。依赖项注入(inject)的最大好处之一是测试变得容易,因为您可以传递由您控制的依赖项。
我假设您想测试类 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));
}
关于java - 谷歌指南 : Mock a @provides method consists of set of object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46201203/