Guice测试是否创建了class

Guice test whether class has been created

我想测试在测试方法期间是否从注入器创建了一个对象的实例。实现此目标的最佳解决方案是什么。

@Test
public void testThingNotInstantiated() {
    AnotherThing another = new AnotherThing(); 
    // assert not instance of Thing created
}

如果您只是想检查 Guice 是否注入了您的 AnotherThing,您可以这样写:

Injector injector

@Before {
    injector = Guice.createInjector(new AnotherThingModule());
}

@Test
public void testAnotherThingInstantiated() {
    //act
    AnotherThing another = injector.getInstance(AnotherThing.class);

    //assert
    assertNotNull(another);
}

如果 AnotherThing 是一个 @Singleton 并且您想测试 Guice 没有实例化它两次,您可以这样写:

@Test
public void testSingletonAnotherThingNotInstantiatedTwiceByInjector() {
    //act
    AnotherThing first = injector.getInstance(AnotherThing.class);
    AnotherThing second = injector.getInstance(AnotherThing.class);

    //assert
    assertSame(first, second);
}