我想在下面的JUnit测试类中使用Guice来注入模拟依赖项,特别是资源.我怎样才能做到这一点?
测试
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注入配置.
我将使用自己的示例来展示它,但它很容易适应您的需求.
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);
原文地址:https://www.jb51.cc/java/124263.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。