如何测试Guice AbstractModule的实现? [英] How to test implementations of Guice AbstractModule?

查看:67
本文介绍了如何测试Guice AbstractModule的实现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在一个大型项目中测试Guice AbstractModule的实现而不创建假实现?是否可以测试bind()和inject()方法?

解决方案

通常,测试Guice模块的最佳方法是在测试中创建一个注入器,并确保可以从中获取自己关心的键的实例./p>

要执行此操作而不会引起生产问题,您可能需要将某些模块替换为其他模块.您可以使用Modules.override有选择地覆盖单个绑定,但是通常最好不要安装生产"类型的模块,而使用伪造的绑定.

从Guice 4.0开始,有一个帮助器类 BoundFieldModule 可以提供帮助.我经常设置如下测试:

 public final class MyModuleTest {
  @Bind @Mock DatabaseConnection dbConnection;
  @Bind @Mock SomeOtherDependency someOtherDependency;

  @Inject Provider<MyThing> myThingProvider;

  @Before public void setUp() {
    MockitoAnnotations.initMocks(this);
    Guice.createInjector(new MyModule(), BoundFieldModule.of(this))
        .injectMembers(this);
  }

  @Test public void testCanInjectMyThing() {
    myThingProvider.get();
  }
}
 

Guice Wiki上还有BoundFieldModule文档.

How to test implementations of Guice AbstractModule in a big project without creating fake implementations? Is it possible to test bind() and inject() methods?

Typically the best way to test Guice modules is to just create an injector in your test and ensure you can get instances of keys you care about out of it.

To do this without causing production stuff to happen you may need to replace some modules with other modules. You can use Modules.override to selectively override individual bindings, but you're usually better off just not installing "production" type modules and using faked bindings instead.

Since Guice 4.0 there's a helper class BoundFieldModule that can help with this. I often set up tests like:

public final class MyModuleTest {
  @Bind @Mock DatabaseConnection dbConnection;
  @Bind @Mock SomeOtherDependency someOtherDependency;

  @Inject Provider<MyThing> myThingProvider;

  @Before public void setUp() {
    MockitoAnnotations.initMocks(this);
    Guice.createInjector(new MyModule(), BoundFieldModule.of(this))
        .injectMembers(this);
  }

  @Test public void testCanInjectMyThing() {
    myThingProvider.get();
  }
}

There's more documentation for BoundFieldModule on the Guice wiki.

这篇关于如何测试Guice AbstractModule的实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆