Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Mock Injected Dependencies

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

}
like image 626
Ari Avatar asked Nov 04 '13 16:11

Ari


People also ask

How do you mock injected objects?

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.

Is mocking a dependency injection?

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.

What is inject mock?

@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.

How do you mock inject an interface?

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()).


1 Answers

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);
like image 192
Aleksandr Kravets Avatar answered Oct 12 '22 09:10

Aleksandr Kravets