Java – how to simulate injected dependencies

I want to use Guice in the JUnit test class below to inject simulation dependencies, especially resources How can I do this?

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));
    }

}

resources

@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);
    }

}

Solution

Consider using another test module to override the Guice injection configuration

I'll use my own example to show it, 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);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>