在单元测试期间创建自定义@TestScoped Guice范围 [英] Creating a custom @TestScoped Guice scope for the duration of a unit test
本文介绍了在单元测试期间创建自定义@TestScoped Guice范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想确定对象的范围,以便它们在单元测试期间以单例形式存在.该模式将遵循在Google Guice中已经实现的@RequestScoped和@SessionScoped,范围将围绕junit测试的@Before和@After:
I would like to scope objects so that they exist as singletons for the duration of a unit test. The pattern would follow the @RequestScoped and @SessionScoped already implemented in Google Guice, by would scope around the @Before and the @After of a junit test:
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可以吗?
Is this possible with Google Guice ?
推荐答案
如果您使用GuiceBerry(基本上是用于测试的Guice/jUnit),则可以使用@TestScoped
if you use GuiceBerry (basically Guice for tests / jUnit), you can use @TestScoped
import com.google.guiceberry.TestScoped;
@Provides
@TestScoped
FlyingSquirrel provideFlyingSquirrel() {
return new WhaleFlyingSquirrelImpl(42);
}
这篇关于在单元测试期间创建自定义@TestScoped Guice范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文