Junit5 简单教程

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");
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值