静态或非静态方法中的 JUnit 测试数据

JUnit test data in static or non static methods

想知道哪个好

我必须将一些 JUnit 测试数据保存在不同的文件中。让我们称它为 TestingData.java。我想到了两种方式。

第一种方式

TestingData.java

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

第二种方式

TestingData.java

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

我可以通过扩展 TestingData class

在我的测试服务中像这样调用 First Way
@RunWith(MockitoJUnitRunner.class)
public class SomeServiceTest extends TestingData {
  @Test
  public void helloWorldTest() {
    assertEquals("Hello World", getHelloWorld());
  }
}

通过调用静态函数 TestingData.getHelloWorld()

在我的测试服务中调用 Second Way
@RunWith(MockitoJUnitRunner.class)
public class SomeServiceTest {
  @Test
  public void helloWorldTest() {
    assertEquals("Hello World", TestingData.getHelloWorld());
  }
}

想知道在干净代码原则上哪种方式更好

答案可能与“干净的代码”无关,而是根据您当前和未来的用例而有所不同。

First Way 中扩展夹具 class 会产生一个重要的限制 - 您将无法扩展任何其他基础 class,并且这种情况在单元测试中经常发生。

无法重写第二种方式中的静态方法。

您可以使用 Third Way,一个带有默认方法的接口。这不会将您限制到特定的基础 class,如果您将来需要它,它的默认方法可能会被覆盖:

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());
  }
}

如果您有多个测试 classes 共享同一个 parent。您可以定义 abstract class 并放置所有公共属性和行为。

,而且我建议将静态内容声明为 static final 不进行硬编码。

通过这种方式,您可以选择创建一个方法并在每个测试用例中从 child 调用它,像这样:

public abstract class TestingData {
  
  private static final GET_HELLO_WORLD = "Hello World";

  public void setUp() {
      // common setUp
  }

  protected String getHelloWorld() {
    return GET_HELLO_WORLD;
  }
}
@RunWith(MockitoJUnitRunner.class)
public class SomeServiceTest extends TestingData {

  @Before
  public void setUp() {
      super.setUp();
      // Add more settings
  }
  
  @Test
  public void helloWorldTest() {
    assertEquals("Hello World", getHelloWorld());
  }
}

,或者直接调用child中的常量

public abstract class TestingData {
  
  protected static final GET_HELLO_WORLD = "Hello World";

  public void setUp() {
      // common setUp
  }
}
@RunWith(MockitoJUnitRunner.class)
public class SomeServiceTest extends TestingData {

  @Before
  public void setUp() {
      super.setUp();
      // Add more settings
  }
  
  @Test
  public void helloWorldTest() {
    assertEquals(callTargetTestMethod(), GET_HELLO_WORLD);
  }
}