Nested Test Setup for Static Inner Test Classes in JUnit4

sekky :

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

Srinivasan Sekar :

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

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=157002&siteId=1