我想在下面的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);