我想在下面的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);
}
}
答案 0 :(得分:10)
考虑使用其他测试模块覆盖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);
答案 1 :(得分:3)
一种选择是在创建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);