以下代码始于JUnit4,除main()之外,大部分已转换为JUnit5。我以这种方式编写代码的原因是,我正在演示TDD,并且我拥有StringInverter实现的多个版本,每个版本都实现了更多功能并通过了更多测试。这是StringInverter接口(interface):

interface StringInverter {
  public String invert(String str);
}

这是几乎与JUnit5一起编译的类:

import java.util.*;
import org.junit.jupiter.api.*;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.platform.runner.JUnitPlatform;

public class StringInverterTest {
  static StringInverter inverter;
  @Test
  public final void basicInversion_Succeed() {
    String in = "Exit, Pursued by a Bear.";
    String out = "eXIT, pURSUED BY A bEAR.";
    assertEquals(inverter.invert(in), out);
  }
  @Test
  public final void basicInversion_Fail() {
    expectThrows(RuntimeException.class, () -> {
      assertEquals(inverter.invert("X"), "X");
    });
  }
  @Test
  public final void allowedCharacters_Fail() {
    expectThrows(RuntimeException.class, () -> {
      inverter.invert(";-_()*&^%$#@!~`");
      inverter.invert("0123456789");
    });
  }
  @Test
  public final void allowedCharacters_Succeed() {
    inverter.invert("abcdefghijklmnopqrstuvwxyz ,.");
    inverter.invert("ABCDEFGHIJKLMNOPQRSTUVWXYZ ,.");
  }
  @Test
  public final void lengthLessThan26_Fail() {
    String str = "xxxxxxxxxxxxxxxxxxxxxxxxxx";
    assertTrue(str.length() > 25);
    expectThrows(RuntimeException.class, () -> {
      inverter.invert(str);
    });
  }
  @Test
  public final void lengthLessThan26_Succeed() {
    String str = "xxxxxxxxxxxxxxxxxxxxxxxxx";
    assertTrue(str.length() < 26);
    inverter.invert(str);
  }
  public static void main(String[] args) throws Exception{
    assertEquals(args.length, 1);
    inverter = (StringInverter)
      Class.forName(args[0]).newInstance();
    Result result = org.junit.runner.JUnitCore.runClasses(
      StringInverterTest.class);
    List<Failure> failures = result.getFailures();
    System.out.printf("%s has %d FAILURES:\n",
      args[0], failures.size());
    int count = 1;
    for(Failure f : failures) {
      System.out.printf("Failure %d:\n", count++);
      System.out.println(f.getDescription());
      System.out.println(f.getMessage());
    }
  }
}
main()与JUnit4一起使用,所以我的问题是如何将其转换为JUnit5。谢谢!

最佳答案

JUnit5在junit-platform-launcher模块中具有启动器API,用于程序化测试发现和执行。
详细的示例记录在其user guide chapter7上。

关于junit5 - Junit 5中的org.junit.runner.JUnitCore.runClasses等效于什么?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39111501/

10-12 22:39