3

I read about the possibility of creating inner test classes with JUnit to better structure tests here: Test cases in inner classes with JUnit

This works rather well and all, but now I am confronted with one problem that I cannot solve elegantly: I would like to have some common test setup accross all tests and some additional setup for individual inner classes.

My structure looks something like this:

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;

import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

@RunWith(Enclosed.class)
public class CalculatorTest {
  private Calculator calc; // class under test

  @Mock
  private Object someMockObject;

  @Before
  public void setUp() {
    // common setup
    MockitoAnnotations.initMocks(this);
    calc = new Calculator();

    when(someMockObject.toString()).thenReturn("my happy little mock object");
  }

  public static class AddTests {
    @Before
    public void setUp() {
      // test setup specifically for this class
      when(someMockObject.toString()).thenReturn("does not compile :(");
    }

    @Test
    public void shouldAddTwoIntegers() {
      int result = calc.add(2, 5);
      assertEquals(7, result);
    }
  }
}

My problem is, that the inner classes need to be static, but I would like to reference the common setup from the enclosing class. Doing so will (obviously) result in the following error:

Cannot make a static reference to the non-static field someMockObject

Is there any way to nest the setups? Or do I need to set up every class in turn (and therefore duplicate code)?

Java Version used: Java8
Libraries used: JUnit4, Mockito2.12

sekky
  • 834
  • 7
  • 14

1 Answers1

1

Remove static from nested class , run with @RunWith(NestedRunner.class)

add junit-runners from com.nitorcreations to pom.xml.

Srinivasan Sekar
  • 2,049
  • 13
  • 22
  • As mentioned in the answer I linked, this does not work since the inner classes need to be static in order for the test runner to execute them correctly. Unless I am missing something? – sekky May 17 '19 at 07:23
  • I tried your suggestion and it works well. The one downside about using the library is, that I am working in a legacy system that manages dependencies via OSGi Manifest files and the nitocreations library is not OSGi-ready... so I have to include the JAR as a resource, which I would like to avoid – sekky May 17 '19 at 08:04