我想限制对象的范围,以便它们在单元测试期间作为单例存在。该模式将遵循 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/