Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JUnit Enclosed runner and shared setup

Tags:

java

junit

I'm experimenting with the JUnit Enclosed runner in order to try and improve the organisation of some of my tests. At the moment I'm trying to work out how to share some setup between the inner classes.

Attempt the first:

@RunWith(Enclosed.class)
public class EnclosedTest {

    @Before
    public void printSomething() {
        System.out.println("Helllooo Meggan");
    }

    public static class FirstTest {

        @Test
        public void assertThatSomethingIsTrue() {
            assertThat(true, is(true));
        }
    }

    public static class SecondTest {

        @Test
        public void assertThatSomethingIsFalse() {
            assertThat(false, is(false));
        }
    }
}

Unfortunately, no-one says hello to Meggan. If I update an inner class to extend the outer one, then I get the following:

java.lang.Exception: class 'org.scratch.EnclosedTest$FirstTest' (possibly indirectly) contains itself as a SuiteClass
at org.junit.runners.model.InitializationError.<init>(InitializationError.java:32)

Is there a particular Enclosed idiom to use when trying to share setup between inner test classes? I was hoping it would be as simple as the C# example I found.

like image 606
chooban Avatar asked Nov 06 '14 09:11

chooban


1 Answers

Enclosed runner internally works as a Suite, that is, it runs the classes as Test cases. And since Junit 4.12 abstract inner classes are ignored by Enclosed runner.

That said the way to share set up is to create an abstract class containing it (@Before, @After):

@RunWith(Enclosed.class)
public class EnclosedTest {

  abstract public static class SharedSetUp {
    @Before
    public void printSomething() {
      System.out.println("Helllooo Meggan");
    }
  }

  public static class FirstTest extends SharedSetUp {
    @Test
    public void assertThatSomethingIsTrue() {
      assertThat(true, is(true));
    }
  }

  public static class SecondTest extends SharedSetUp {
    @Test
    public void assertThatSomethingIsFalse() {
      assertThat(false, is(false));
    }
  }
}

Notice that you can even declare custom runners for each subclass.

like image 55
Gonzalo Matheu Avatar answered Oct 06 '22 00:10

Gonzalo Matheu