java - 在单元测试期间创建自定义 @TestScoped Guice 范围

标签 java unit-testing junit dependency-injection guice

我想限制对象的范围,以便它们在单元测试期间作为单例存在。该模式将遵循 Google Guice 中已实现的 @RequestScoped 和 @SessionScoped,范围围绕 junit 测试的 @Before 和 @After:

public class MyUnitTest {
    @TestScoped static class MyTestScopedClass { }

    @Before public void enterTestScope() {
        // something here creates the TestScope
    }

    @After public void exitTestScope() {
        // destroy the TestScope
    }

    @Test public void MyTest() {
        // MyTest instantiates object using injection, some are @Singletons
        // and will remain for other tests, but those that are @TestScoped
        // will be created once for this test and will be automatically 
        // destroyed at the end of this test
    }
} 

这可以通过 Google Guice 实现吗?

最佳答案

如果你使用GuiceBerry(基本上是用于测试/jUnit的Guice),你可以使用@TestScoped

import com.google.guiceberry.TestScoped;

@Provides
@TestScoped
FlyingSquirrel provideFlyingSquirrel() {
  return new WhaleFlyingSquirrelImpl(42);
}

关于java - 在单元测试期间创建自定义 @TestScoped Guice 范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32444723/

相关文章:

java - openjdk gervill软件混音器的声音输出在哪里

java - Junit 未获取 persistance.xml EJB3

unit-testing - 您如何对不同的类访问级别进行单元测试?

python - 在tkinter中生成点击事件

java - 无法在 Ubuntu Linux 上运行 JxBrowser Java 应用程序

java - Android - 从 Activity 到广播接收器获取偏好

c# - 将传递的参数设置为 Moq 中的特定值

java - Eclipse 在错误的目录中创建 JUnit 测试

java - Mockito 中的嵌套方法模拟

java - 有效的 JUnit 测试