springboot2.2.x的单元测试demo:
import org.junit.jupiter.api.*;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public class DemoTest {
@BeforeAll
public static void beforeAll(){
System.out.println("beforeAll");
}
@BeforeEach
public void beforeEach(){
System.out.println("beforeEach");
}
@AfterEach
public void afterEach(){
System.out.println("afterEach");
}
@AfterAll
public static void afterAll(){
System.out.println("afterAll");
}
@Test
public void test(){
System.out.println("test");
}
}
测试的执行顺序依次为beforeAll、beforeEach、test、afterEach、afterAll,运行spring上下文环境只需加注解@springBootTest,无需加junit4下的@RunningWith注解。
与junit4的注解对比
| JUnit4 | JUnit5 | 说明 |
|---|---|---|
| @Test | @Test | 表示该方法是一个测试方法。JUnit5与JUnit 4的@Test注解不同的是,它没有声明任何属性,因为JUnit Jupiter中的测试扩展是基于它们自己的专用注解来完成的。这样的方法会被继承,除非它们被覆盖 |
| @BeforeClass | @BeforeAll | 表示使用了该注解的方法应该在当前类中所有使用了@Test @RepeatedTest、@ParameterizedTest或者@TestFactory注解的方法之前 执行; |
| @AfterClass | @AfterAll | 表示使用了该注解的方法应该在当前类中所有使用了@Test、@RepeatedTest、@ParameterizedTest或者@TestFactory注解的方法之后执行; |
| @Before | @BeforeEach | 表示使用了该注解的方法应该在当前类中每一个使用了@Test、@RepeatedTest、@ParameterizedTest或者@TestFactory注解的方法之前 执行 |
| @After | @AfterEach | 表示使用了该注解的方法应该在当前类中每一个使用了@Test、@RepeatedTest、@ParameterizedTest或者@TestFactory注解的方法之后 执行 |
| @Ignore | @Disabled | 用于禁用一个测试类或测试方法 |
| @Category | @Tag | 用于声明过滤测试的tags,该注解可以用在方法或类上;类似于TesgNG的测试组或JUnit 4的分类。 |
| @Parameters | @ParameterizedTest | 表示该方法是一个参数化测试 |
| @RunWith | @ExtendWith | @Runwith就是放在测试类名之前,用来确定这个类怎么运行的 |
| @Rule | @ExtendWith | Rule是一组实现了TestRule接口的共享类,提供了验证、监视TestCase和外部资源管理等能力 |
| @ClassRule | @ExtendWith | @ClassRule用于测试类中的静态变量,必须是TestRule接口的实例,且访问修饰符必须为public。 |
junit5基于java8写的,要求最低版本为java8。junit的一些新特性有支持lambda表达式和分组判定等
@Test
void lambdaTest(){
assertTrue(1>2,()->"111");
}
@Test
void groupTest(){
List<String> list= Lists.newArrayList("12","34");
assertAll("list",()->assertEquals("12",list.get(0)),()->assertEquals("34",list.get(1)));
}
单元测试与集成测试区别,以及spring下的mock测试
junit官网链接
https://junit.org/junit5/docs/current/user-guide/#overview-what-is-junit-5
本文介绍了SpringBoot 2.2.x版本中进行单元测试的方法,强调了与JUnit 4注解的区别,如使用@SpringBootTest注解即可运行spring上下文环境。同时探讨了单元测试与集成测试的差异,并提到了Spring下的mock测试。此外,还提供了JUnit 5的官方链接供参考。
2304

被折叠的 条评论
为什么被折叠?



