如何模拟注入的依赖项

9

我想在下面的JUnit测试类中使用Guice来注入模拟依赖项,具体是resource。 我该怎么做?

测试

public class SampleResourceTest extends ResourceTest {  

    @Override
    protected void setUpResources() throws Exception {
        // when(dao.getSample(eq("SIP"), eq("GA"))).thenReturn(sam);
        addResource(new SampleResource());
    }

    @Test
    public void getSampleTest() {
        Assert.assertEquals(sam, client().resource("/sample/SIP/GA").get(Sample.class));
    }

}

资源

@Path("/sample")
@Produces(MediaType.APPLICATION_JSON)
public class SampleResource {   

    @Inject
    private SampleDao samDao;

    @GET
    @Path("/{sample}/{id}")
    public Sample getSample(@PathParam("id") String id) {
        return samDao.fetch(id);
    }

}

你想将DAO注入到单元测试中吗?或者你已经将DAO注入到了你实际测试的类中了吗? - rmlan
抱歉,我需要将“Resource”注入到单元测试中,并在注入的“Resource”内部模拟“DAO”。 - Ari
你能展示一下资源的代码吗?DAO是如何声明和使用的? - rmlan
1
你尝试过使用 @InjectMocks 吗? - anstarovoyt
好的,这很有帮助,但还有一个问题,然后我想我就能回答你了。你的注入器在哪里创建/使用? - rmlan
@rmlan 目前还没有注入器。但我认为它应该/会放在SampleResourceTest用例的主体中。 - Ari
2个回答

12

考虑使用另一个测试模块覆盖您的Guice注入配置。

我将使用自己的示例来演示,但很容易适应您的需求。

Module testModule = Modules.override(new ProductionModule())
    .with(new AbstractModule(){

    @Override
    protected void configure() {
        bind(QueueFactory.class).toInstance(spy(new QueueFactory()));
    }

});

Injector injector = Guice.createInjector(testModule);
QueueFactory qFactorySpy = injector.getInstance(QueueFactory.class);

5

一种选择是在创建Guice注入器时将Mock DAO实例绑定到DAO类。然后,当您添加SampleResource时,使用getInstance方法代替。像这样:

Injector injector = Guice.createInjector(new AbstractModule() {
        @Override
        protected void configure() {
            bind(SampleDao.class).toInstance(mockDao);
        }
});

addResource(injector.getInstance(SampleResource.class);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接