4

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?

durron597
  • 31,968
  • 17
  • 99
  • 158
Arshan Qureshi
  • 106
  • 2
  • 6

1 Answers1

4

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();
Tavian Barnes
  • 12,477
  • 4
  • 45
  • 118
  • What's the syntax for providing multiple arguments to a resource in this way? – Arshan Qureshi Jul 08 '15 at 10:57
  • I don't know because I don't know dropwizard. How were you doing it before? – Tavian Barnes Jul 08 '15 at 15:57
  • It's not related to DW, my question was If we have a Class with two parameters, let's say xyz, and xyz2 , How do you pass these two arguments to a class when instantiating a new object. new AbcResource(() -> xyz ) would only pass one argument, how do you provide the second argument xyz2 ? – Arshan Qureshi Jul 09 '15 at 05:53
  • 1
    Um, `new AbcResource(() -> xyz, () -> xyz2)`? – Tavian Barnes Jul 09 '15 at 13:33