lundi 7 septembre 2015

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

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 ?

Aucun commentaire:

Enregistrer un commentaire