3

I am creating a new @Rule for my use case which looks like

public class ActiveDirectoryConfigurationRule extends ExternalResource {

  @Rule
  public TemporaryFolder temporaryFolder = new TemporaryFolder();

  public File addActiveDirectoryConfigurationToFile(ActiveDirectoryConfiguration configuration) throws IOException {
    File file = temporaryFolder.newFile();
    objectMapper.writeValue(file, configuration);
    return file;
  }

  private ObjectMapper registerJdk8ModuleAndGetObjectMapper() {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.registerModule(new Jdk8Module());
    return objectMapper;
  }
}

In my Test I use it as

public class ActiveDirectoryConfigurationStoreTest {

      @Rule
      public ActiveDirectoryConfigurationRule configurationRule = new ActiveDirectoryConfigurationRule();

          @Test
          public void getWhenConfigurationExists() throws Exception {
            ActiveDirectoryConfiguration activeDirectoryConfiguration = //....;
            File configurationToFile = configurationRule.addActiveDirectoryConfigurationToFile(activeDirectoryConfiguration);

            ActiveDirectoryConfigurationStore configurationStore = new ActiveDirectoryConfigurationStore(configurationToFile);
            Optional<ActiveDirectoryConfiguration> mayBeConfiguration = configurationStore.getConfiguration();
            assertTrue(mayBeConfiguration.isPresent());
          }
        }

When I run this test, I get error as

java.lang.IllegalStateException: the temporary folder has not yet been created

    at org.junit.rules.TemporaryFolder.getRoot(TemporaryFolder.java:145)
    at org.junit.rules.TemporaryFolder.newFile(TemporaryFolder.java:78)
    at com.conf.store.ActiveDirectoryConfigurationRule.addActiveDirectoryConfigurationToFile(ActiveDirectoryConfigurationRule.java:48)
    at com.conf.store.ActiveDirectoryConfigurationStoreTest.getWhenConfigurationExists(ActiveDirectoryConfigurationStoreTest.java:25)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.rules.ExternalResource$1.evaluate(ExternalResource.java:48)
    at org.junit.rules.RunRules.evaluate(RunRules.java:20)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:119)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:234)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:74)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)

Seems like when creating your own @Rule, I am not able to depend on any existing @Rule

Is that the issue? and how do I resolve it?

daydreamer
  • 87,243
  • 191
  • 450
  • 722

2 Answers2

3

Yes, I don't think that there's anything built in to JUnit to let you "nest" @Rule objects like you're doing.

I think the most obvious options would be:

  1. In your custom @Rule, call the various methods on your child @Rule at the appropriate times. (Essentially, pretend that you are the JUnit library, using the @Rule per its interface.) I haven't dug into the details to see how complex it would be.
  2. Have your @Rule extend TemporaryFolder rather than ExternalResource, making sure to call super() in any of the methods you're overriding. This lets you do "Everything a TemporaryFolder does and then some", which perhaps isn't perfect OO-theory (as it's not really a type-of TemporaryFolder) but should work the way you're looking for. I've used this approach when setting up a particular folder that needed to be set up with a particular environment for my tests, and it worked fairly well.
  3. Have your custom @Rule take in as a constructor parameter a TemporaryFolder reference, which you then save in a field and use as needed. This requires all users of your @Rule to include both @Rule objects, but perhaps makes it clear that the test really does require both a temporary folder to do its work in as well as your particular custom setup.
  • 1
    Option #3 sounds like the best design. However, I think it'll be hard to implement: You want to guarantee that `TemporaryFolder` has been instantiated first, so you can pass it to your custom `Rule`. For that purpose JUnit has a `RuleChain` (http://www.hascode.com/2012/02/ordering-your-junit-rules-using-a-rulechain/). Here you can define the order, but not pass one instance to the constructor of the other. A real dilemma! I think option #1 is pragmatic: Override `apply(...)`, wrap your `Statement` around the one generated by `TemporaryFolder` and execute your logic after your child rule. – Peter Wippermann Jul 22 '16 at 11:33
  • I like the approach #3 as well, I will read about `RuleChain` – daydreamer Jul 22 '16 at 18:10
1

There is no support for declaring rules with @Rule inside of rules. But you can manually run the other rule.

public class ActiveDirectoryConfigurationRule implements TestRule {

  private TemporaryFolder temporaryFolder = new TemporaryFolder();

  @Override
  public Statement apply(Statement base, Description description) {
    Statement testWrappedWithYourCode = new Statement() {
      public void evaluate() {
        before();

        List<Throwable> errors = new ArrayList<Throwable>();
        try {
          base.evaluate();
        } catch (Throwable t) {
          errors.add(t);
        } finally {
          try {
            after();
          } catch (Throwable t) {
            errors.add(t);
          }
        }
        MultipleFailureException.assertEmpty(errors);
      }
    }

    return temporaryFolder.apply(testWrappedWithYourCode, description);
  }

  public File addActiveDirectoryConfigurationToFile(ActiveDirectoryConfiguration configuration) throws IOException {
    File file = temporaryFolder.newFile();
    objectMapper.writeValue(file, configuration);
    return file;
  }

  private ObjectMapper registerJdk8ModuleAndGetObjectMapper() {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.registerModule(new Jdk8Module());
    return objectMapper;
  }
}
Stefan Birkner
  • 24,059
  • 12
  • 57
  • 72