Search code examples
javajunit4guicedropwizardjukito

How do I inject dependencies in Junit test case using Guice before @Rule runs?


Frameworks I'm working with are Dropwizard 7, Guice and for testing we have Junit with Jukito. I have a resource written in dw and I need to write a test case corresponding to that resource. Note: We recently migrated from dw 6 to dw 7.

In dw 6 we had test cases like :

@RunWith(JukitoRunner.class)
public class AbcResourceTest extends ResourceTest{
  @Inject
  private Provider<XyzAction> xyzProvider;
  public void setUpResources() throws Exception {
   addResource(new AbcResource(xyzProvider));
  }
  @Test
  public void doTesting() {
  }
}

This method worked just fine, Guice would inject all the dependency and the resource would initialise just fine.

But in DW 7 the syntax for writing resource test changed to the following

public class ResourceTest {
 PersonDao personDao = mock(PersonDao.class);
 @Rule public ResourceTestRule resources = ResourceTestRule
      .builder()
      .addResource(new Resource(personDao))
      .build();
}

This is an example from the dw documentation and works fine. But if instead of mocking PersonDao if i try to inject something like this:

@RunWith(JukitoRunner.class)
public class AbcResourceTest {
  @Inject
  private Provider<XyzAction> xyzProvider;
 @Rule public ResourceTestRule resources = ResourceTestRule
      .builder()
      .addResource((new AbcResource(xyzProvider))
      .build();
  @Test
  public void doTesting() {
  }
}

This code instantiates the resource with null value for xyzProvider. Although Guice does instantiates the xyzProvider but only after @Rule has been evaluated. Now my problem is that i want Guice to inject dependency before @Rule is evaluated. Is there a way to make that happen?


Solution

  • I suspect that JukitoRunner will cause injection to happen before the @Rule runs. But what it can't do is cause injection to happen before the constructor finishes. Something like this might work (Java 8 syntax):

    @Inject
    private XyzAction xyz;
    
    @Rule
    public ResourceTestRule resources = ResourceTestRule
            .builder()
            .addResource(new AbcResource(() -> xyz))
            .build();