JUnit5由JUnit Platform、JUnit Jupiter、JUnit Vintage构成
SpringBoot2.4以上移除了Vintage部分,如果需要使用JUnit4需要自行引入
基本常用测试注解:
/**
* //SpringBoot的派生注解
* @BootstrapWith(SpringBootTestContextBootstrapper.class)
* @ExtendWith({SpringExtension.class}) //表示使用Spring的测试驱动进行测试
*/
@SpringBootTest
@DisplayName("JUnit5功能测试")
public class Junit5Test {
@Autowired
JdbcTemplate jdbcTemplate;
@Test
@DisplayName("test1方法") //给测试类或者方法取一个名称,方便识别
public void test1(){
System.out.println(1);
System.out.println(jdbcTemplate);
}
@Test
@DisplayName("test2方法")
@Disabled //当前测试方法不执行
public void test2(){
System.out.println(2);
}
@Test
@Timeout(1) //规定方法的超时时间,超时则表示测试异常
public void test3() throws InterruptedException {
Thread.sleep(2000);
System.out.println("测试timeout");
}
@RepeatedTest(5)
@Test
@DisplayName("重复测试5次")
public void test4(){
System.out.println("重复测试5次");
}
@BeforeEach //在每个单元执行前执行该方法
public void beforeEach(){
System.out.println("在每个单元执行前");
}
@AfterEach //在每个单元执行后执行该方法
public void afterEach(){
System.out.println("在每个单元执行后");
}
@BeforeAll //在所有单元执行前执行该方法
public static void beforeAll(){
System.out.println("在所有单元执行前");
}
@AfterAll //在所有单元执行后执行该方法
public static void afterAll(){
System.out.println("在所有单元执行后");
}
@Test
@DisplayName("测试简单断言")
public void testDy1(){
int c=cal(2,3);
//判断相等,当前断言失败后面的代码不会执行
assertEquals(6,c,"计算失败");
Object o1=new Object();
Object o2=new Object();
assertSame(o1,o2,"不是同一个对象");
}
public int cal(int x,int y){
return x+y;
}
@Test
@DisplayName("测试数组相等断言")
public void testDy2(){
assertArrayEquals(new int[]{1,2},new int[]{2,1},"数组不相等");
}
@Test
@DisplayName("测试组合断言")
public void testDy3(){
//任意一个子断言失败,总断言就是失败
assertAll("testAll",()->assertTrue(true && false,"结果为false"),()->assertEquals(2,1,"不相等"));
System.out.println("子断言全部成功才执行");
}
@Test
@DisplayName("异常断言")
public void testDy4(){
//断定业务逻辑一定会出异常
assertThrows(ArithmeticException.class,()->{int a=10/3;},"居然没有算术异常!!");
}
@Test
@DisplayName("快速失败")
public void testDy5(){
if(1==1){
fail("快速失败");
}else{
//测试成功
}
}
@Test
@DisplayName("测试前置条件")
public void testDy6(){
//前置条件是继续测试的前提,当前置条件不满足,就没有继续测试的必要了
assertTrue(false,"测试结果非true");
System.out.println("执行了吗");
}
@ParameterizedTest
@DisplayName("参数化测试")
@ValueSource(ints = {1,3,6,4,7})
public void testDy7(int i){
System.out.println("数字:"+i);
}
@ParameterizedTest
@DisplayName("方法的参数化测试")
@MethodSource("stringStream") //方法的参数化测试必须返回流,方法必须是静态的
public void testDy8(String s){
System.out.println("字母是:"+s);
}
static Stream<String> stringStream(){
return Stream.of("apple","orange");
}
}
断言测试的好处是:在所有的测试运行结束以后,会有一个详细的测试报告;