junit。它引入了一些强大的功能和增强功能,使编写、组织和运行测试变得更加容易。了解这些高级功能可以帮助您创建更健壮且可维护的测试套件。
什么是 junit 5?
junit 5 是 junit 框架的重大更新,旨在更加灵活和模块化。它由三个主要部分组成:
- junit platform:在 jvm 上启动测试框架的基础。
- junit jupiter:用于编写测试的新编程模型和扩展模型。
- junit vintage:为在 junit 5 平台上运行 junit 3 和 junit 4 测试提供支持。
junit 5 的主要特性
- 显示名称:使用自定义显示名称注释测试以提高可读性。
- 嵌套测试:分层组织测试以反映测试代码的结构。
- 动态测试:在运行时动态创建测试。
- 标记和过滤:使用标签对测试进行分组并在执行过程中对其进行过滤。
- 断言和假设:增强对断言和假设的支持,以控制测试执行流程。
示例:使用 junit 5 的高级功能
- 自定义显示名称:
import org.junit.jupiter.api.displayname;
import org.junit.jupiter.api.test;
import static org.junit.jupiter.api.assertions.assertequals;
@displayname("calculator tests")
class calculatortest {
@test
@displayname("addition test")
void testaddition() {
assertequals(2, 1 + 1, "1 + 1 should equal 2");
}
}
- 嵌套测试:
import org.junit.jupiter.api.nested; import org.junit.jupiter.api.test; class outertest { @nested class innertest { @test void innertest() { // test logic here } } }
- 动态测试:
import org.junit.jupiter.api.dynamictest;
import org.junit.jupiter.api.testfactory;
import java.util.stream.stream;
import static org.junit.jupiter.api.assertions.asserttrue;
import static org.junit.jupiter.api.dynamictest.dynamictest;
class dynamictestsdemo {
@testfactory
stream dynamictests() {
return stream.of(1, 2, 3, 4, 5)
.map(number -> dynamictest("test number " + number, () -> asserttrue(number > 0)));
}
}
- 标记和过滤:
import org.junit.jupiter.api.tag;
import org.junit.jupiter.api.test;
class taggingtest {
@test
@tag("fast")
void fasttest() {
// fast test logic here
}
@test
@tag("slow")
void slowtest() {
// slow test logic here
}
}
- 断言和假设:
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
class AssertionsDemo {
@Test
void testException() {
assertThrows(IllegalArgumentException.class, () -> {
throw new IllegalArgumentException("Exception message");
});
}
@Test
void testAssumption() {
assumeTrue(5 > 1);
// Test logic here
}
}
结论
junit 5 带来了丰富的新功能和改进,使其成为现代 java 测试的强大工具。通过利用这些高级功能,您可以创建更有组织、灵活且可维护的测试套件,确保您的代码健壮且可靠。









