问题
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
}
}
Is this possible with Google Guice ?
回答1:
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);
}
来源:https://stackoverflow.com/questions/32444723/creating-a-custom-testscoped-guice-scope-for-the-duration-of-a-unit-test