Java 如何模拟注入的依赖
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19772247/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to Mock Injected Dependencies
提问by Ari
I'd like to use Guice in the following JUnit test class to inject mock dependencies, specifically the resource
. How can I do this?
我想在以下 JUnit 测试类中使用 Guice 来注入模拟依赖项,特别是resource
. 我怎样才能做到这一点?
Test
测试
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));
}
}
Resource
资源
@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);
}
}
回答by rmlan
One option would be to bind the Mock DAO instance to the DAO class when creating your Guice injector. Then, when you add the SampleResource
, use the getInstance method instead. Something like this:
一种选择是在创建 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);
回答by Aleksandr Kravets
Consider overriding your Guice injection configuration using another test module.
考虑使用另一个测试模块覆盖您的 Guice 注入配置。
I will show it using own example, but it's easy to adapt to your needs.
我将使用自己的示例展示它,但它很容易适应您的需求。
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);