I'd like to use Guice in the following JUnit test class to inject mock dependencies, specifically the resource
. 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));
}
}
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);
}
}
Mockito @InjectMocks annotations allow us to inject mocked dependencies in the annotated class mocked object. This is useful when we have external dependencies in the class we want to mock. We can specify the mock objects to be injected using @Mock or @Spy annotations.
Dependency injection is a way to scale the mocking approach. If a lot of use cases are relying on the interaction you'd like to mock, then it makes sense to invest in dependency injection. Systems that lend themselves easily to dependency injection: An authentication/authorization service.
@InjectMocks is the Mockito Annotation. It allows you to mark a field on which an injection is to be performed. Injection allows you to, Enable shorthand mock and spy injections. Minimize repetitive mock and spy injection.
public class TestDo { @Mock private Do do; @Mock private ABC abc; @Before public void init() { MockitoAnnotations. initMocks(this); do. abc = abc; } @Test public void testDo() { when(do. doAbc()).
Consider overriding your Guice injection configuration using another test module.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With