以下代码从 JUnit4 开始,除了main()
. 我这样写的原因是我正在演示 TDD,并且我有多个版本的StringInverter
实现,每个版本都实现了更多的功能并通过了更多的测试。这是StringInverter
界面:
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,所以我的问题是如何将其转换为 JUnit 5。谢谢!