Creating a custom @TestScoped Guice scope for the duration of a unit test

a 夏天 提交于 2019-12-11 03:55:42

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!