Java 如何模拟注入依赖项
我想在下面的JUnit测试类中使用Guice来注入模拟依赖项,特别是Java 如何模拟注入依赖项,java,junit,guice,mockito,Java,Junit,Guice,Mockito,我想在下面的JUnit测试类中使用Guice来注入模拟依赖项,特别是资源。我该怎么做 测试 public class SampleResourceTest extends ResourceTest { @Override protected void setUpResources() throws Exception { // when(dao.getSample(eq("SIP"), eq("GA"))).thenReturn(sam);
资源
。我该怎么做
测试
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);
}
}
一种选择是在创建Guice注入器时将模拟DAO实例绑定到DAO类。然后,当您添加
SampleResource
时,请改用getInstance方法。大概是这样的:
Injector injector = Guice.createInjector(new AbstractModule() {
@Override
protected void configure() {
bind(SampleDao.class).toInstance(mockDao);
}
});
addResource(injector.getInstance(SampleResource.class);
考虑使用另一个测试模块覆盖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);
是否要将DAO注入单元测试?或者您已经将DAO注入到实际测试的类中了吗?对不起,我需要将
资源
注入单元测试,并在注入的资源
中模拟DAO
,您可以显示资源的代码吗?DAO是如何声明/使用的?您是否尝试@InjectMocks?好的,这很有帮助,但还有一个问题,我想我会为您提供答案。您的喷油器是在哪里创建/使用的?