Annotations
测试类注解
@Test
普通的测试
@RepeatedTest
重复测试
@BeforeEach
void beforeEach(TestInfo testInfo, RepetitionInfo repetitionInfo) {
int currentRepetition = repetitionInfo.getCurrentRepetition();
int totalRepetitions = repetitionInfo.getTotalRepetitions();
}
//重复测试
@RepeatedTest(10, name="{currentRepetition}/{totalRepetitions}") //测试10次,每次展示不同的名字
@ParameterizedTest
重复测试,但是每次测试所用的参数不一样,需要自己补充参数。
//只能提供一个参数,类型可以包括基本类型和java.lang.String,java.lang.Class
@ParameterizedTest
@ValueSource(ints = { 1, 2, 3 })
void testWithValueSource(int argument) {
assertTrue(argument > 0 && argument < 4);
}
@ParameterizedTest
@CsvSource({
"apple, 1",
"banana, 2",
"'lemon, lime', 0xF1",
"strawberry, 700_000"
})
void testWithCsvSource(String fruit, int rank) {
...
}
//numLinesToSkip表示跳过几行
@ParameterizedTest
@CsvFileSource(resources = "/two-column.csv", numLinesToSkip = 1)
void testWithCsvFileSourceFromClasspath(String country, int reference) {
assertNotNull(country);
assertNotEquals(0, reference);
}
辅助类注解
@DisplayName
给测试命名
@BeforeEach
每次测试前执行
@BeforeEach
void beforeEach(){...}
@AfterEach
每次测试后执行
@BeforeAll
所有测试前执行
@AfterAll
所有测试后执行
Assertions
assertEquals(a, b)
比较a和b是否相同
assertTrue©
判断语句c是否为true
代码示例
class CalculatorTests {
//辅助类函数
//@AfterEach
//测试函数
@Test
@DisplayName("1 + 1 = 2")
void addsTwoNumbers() {
Calculator calculator = new Calculator();
//Assertions
assertEquals(2, calculator.add(1, 1), "1 + 1 should equal 2");
}
}