Search code examples
javajava-8coding-stylejunit4

JUnit test data in static or non static methods


Like to know which one is good.

I have to keep some JUnit test data in a different file. Lets call it as TestingData.java. I thought of doing it in two ways.

First Way

TestingData.java

public class TestingData {
  protected String getHelloWorld() {
    return "Hello World";
  }
}

Second Way

TestingData.java

public class TestingData {
  public static String getHelloWorld() {
    return "Hello World";
  }
}

I can call the First Way like this in my testing service by extends TestingData class

@RunWith(MockitoJUnitRunner.class)
public class SomeServiceTest extends TestingData {
  @Test
  public void helloWorldTest() {
    assertEquals("Hello World", getHelloWorld());
  }
}

calling Second Way in my testing service by calling the static function TestingData.getHelloWorld()

@RunWith(MockitoJUnitRunner.class)
public class SomeServiceTest {
  @Test
  public void helloWorldTest() {
    assertEquals("Hello World", TestingData.getHelloWorld());
  }
}

Like to know which way is better in clean code principle


Solution

  • The answer might not be related to "clean code", but rather be different depending on your current and future use cases.

    Extending the fixture class in the First Way creates an important limitation - you won't be able to extend any other base class, and such case happens quite often in unit testing.

    A static method in the Second Way can't be overridden.

    You could use a Third Way, an interface with a default method. This won't limit you to a specific base class, and its default method may be overridden if you need this in the future:

    public interface TestingData {
      default String getHelloWorld() {
        return "Hello World";
      }
    }
    
    @RunWith(MockitoJUnitRunner.class)
    public class SomeServiceTest implements TestingData {
      @Test
      public void helloWorldTest() {
        assertEquals("Hello World", getHelloWorld());
      }
    }