4

I have organised my junit tests using one inner class per method as described:

Here, in a haacked article (about nunit testing), and
Here, in this SO question

public class TestMyThing {

    public static class TestMyThingMethodOne {

        @Test
        public void testMethodOneDoesACertainBehaviour() {
            // terse, clear testing code goes here
        }

        @Test
        public void testMethodOneHasSomeOtherDesiredBehaviour() {
            // more inspiring testing code here
        }
    }

    public static class TestMyThingMethodTwo {
        ... etc
    }
}

However, when I try to run the junit tests for this, Eclipse asks me which of the inner class tests I want to run and I can only choose one. Is there a way I can specify that I want every test in every inner class for the TestMyThing class to run?

Community
  • 1
  • 1
Joe
  • 4,562
  • 9
  • 55
  • 79

2 Answers2

7

I asked my question on the Eclipse forum in this post and it turns out that it is possible for Eclipse to run all the inner classes. I quote the reply, which I've tried and can confirm that it works great (i.e. I can call all of the tests in my inner classes with one command):

JUnit 4 comes with a runner class called Enclosed, which does what you need.

Annotate the outer class with @RunWith(Enclosed.class) with Enclosed = import org.junit.experimental.runners.Enclosed;

Community
  • 1
  • 1
Joe
  • 4,562
  • 9
  • 55
  • 79
2

Usually you would just create separate classes ( just pojos with default constructor ) instead of packing distinct unit tests into single class. As your inner classes are static, there is no real advantage in doing this.

Konstantin Pribluda
  • 12,042
  • 1
  • 26
  • 34
  • +1. And you could add the fact that most tools, i.e. maven, ant, Eclipse don't cope well with this either. – Matthew Farwell Jan 31 '12 at 13:18
  • 1
    Hmmm, OK. Shame that Eclipse doesn't handle it well, because it's really nice and neat and keeps all the tests for one method together, while still only having one class for all the tests for one class. I'm interested though, when you say "Usually you would just create separate classes..." do you mean separate classes for each method that I'm testing? And when you say "distinct unit tests" how do you define that? Is a unit test all the tests that you do for one method? Thanks for your answer :) – Joe Jan 31 '12 at 21:52
  • I tend to create separate test class for each class under test. And mybe some additional test classes if there is a need for it. – Konstantin Pribluda Feb 01 '12 at 06:28