java - 谷歌指南 : Mock a @provides method consists of set of object

标签 java unit-testing mockito guice

我有一个 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/

相关文章:

java - 使用 Java 将照片上传到 flickr 时签名无效

c# - 使用 Moq 验证委托(delegate)

algorithm - 对复杂算法进行单元测试

java - 当我运行 mockito 测试时发生 WrongTypeOfReturnValue 异常

java - 从 apache HttpResponse 获取响应 Uri 参数

java - 如何在 JNA 中映射枚举

java - 如何启动新的JavaFX(应用程序)线程?

visual-studio-2008 - 为什么在同一测试项目程序集中两次调用[AssemblyInitialize]和[AssemblyCleanup]?

java - Mockito 并不是在 mock 我的背景

java - 为 mockito 导入