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