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

@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);
}

07-25 22:26