简介
JUnit 5 = Junit Platform + JUnit Jupiter + JUnit Vintage
JUnit Vintage 用来兼容 JUnit4.x, JUnit 3.x
SpringBoot 2.4 以上版本移除了默认对 Vintage 的依赖,若需要兼容 JUnit 4.x 需要自行引入
Spring Boot 整合 JUnit 后,Junit 类具有 Spring 的功能,比如可加上 @Autowired, @Transactional
1.2 区别
之前通过加入 SpringRunner,即可使得 Junit 自动完成 Spring 上下文的加载
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ConbootStarterApplication.class)
@SpringBootTest(classes = ConbootStarterApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ConbootStarterApplicationTests {
@Resource
private TestRestTemplate testRestTemplate;
@Resource
private DataSource dataSource;
@LocalServerPort
private int port;
private URL url;
@BeforeEach
public void setUp() throws Exception {
this.url = new URL("http://localhost:" + port + "/web/hello");
}
@Test
public void contextLoads() {
ResponseEntity<String> response = testRestTemplate.getForEntity(url.toString(), String.class);
Assertions.assertEquals(response.getBody(), "hello");
}
}
JUnit 5 常用注解
- @Test
- @BeforeEach / @AfterEach
- @BeforeAll / @AtferAll 方法需要是 static
- @Disabled
断言(Assertions)
- 测试是否满足条件
网友评论