android - 如何覆盖 @ContextSingletons 以使用 RoboGuice 进行测试?

标签 android testing dependency-injection roboguice

我正在尝试覆盖几个注入(inject)以使用特定测试模块进行测试。这对于像这样的真正的单例来说工作得很好:

...custom module...
bind(SomeClass.class).toInstance(instanceOfMockedClass);
...

现在这会在 ContextSingletons 时产生问题需要被覆盖。像上面那样做显然会为所有上下文(服务、 Activity )注入(inject)相同的实例,其中单独的实例是正确的。我试图绕过 ContextScopedProvider但找不到在 bind(...).toProvider(...) 中实际使用它的方法构造,因为此类本身不实现 Guice 的 Provider<T>界面。

如何实现?

(也在 https://groups.google.com/forum/?fromgroups=#!topic/roboguice/MnWGrHFDOsQ 上询问过)

最佳答案

另一种为普通单例编写的方法是这样的

bind(SomeClass.class).toProvider(SomeClassProvider.class).in(Singleton.class);

如果你这样做,你不需要在绑定(bind)时有可用的实例,虽然这对于单例来说很好,但显然不适用于 ContextSingleton,因为还没有上下文。

您可以对 ContextSingleton 使用相同类型的绑定(bind):

bind(SomeClass.class).toProvider(SomeClassProvider.class).in(ContextSingleton.class);

现在,RoboGuice 为您注入(inject)的所有 SomeClass 实例都将被适本地限定范围,无论是 Singleton 还是 ContextSingleton。

关于android - 如何覆盖 @ContextSingletons 以使用 RoboGuice 进行测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16057965/

相关文章:

c# - 结构图 - 构造函数中的依赖集合

java - Spring 注入(inject)的 bean 线程安全

android - 如何从自定义适配器获取 TextView id

java - Pentaho水壶: how to set up tests for transformations/jobs?

android - 2.3 上带有完成 SoftInput 操作标签的多行 EditText

python - pytest fixture 总是返回一个函数

TFS 版本 : Fails to run tests

dependency-injection - 多个项目中的asp.net 5依赖注入(inject)

android - 您真的需要检查 Google Play 服务才能使用 AdMob 吗?

java - TYPE_ROTATION_VECTOR 不适用于某些设备