一、JUit5
和之前的junit版本不一样,junit5是由三个模块组成。
JUnit 5 = JUnit Platform + JUnit Jupiter + JUnit Vintage。
- JUnit Platform是在jvm上启动测试框架的基础,定义了测试引擎的API,可以在cmd命令行启动这个平台。
- JUnit Jupiter是新编程模块和扩展模块在junit5上写测试和扩展的组合,Jupiter子工程提供在平台上跑Jupiter的测试引擎。
- JUnit Vintage提供跑junit3和junit4的测试引擎。
支持的java版本:
junit5需要java8及以上的版本。但是可以测试用以前的jdk版本编译过的代码。
二、maven依赖
<!--JUnit4-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>compile</scope>
</dependency>
<!--JUnit5-->
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-launcher</artifactId>
<version>1.0.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.0.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>4.12.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.6.0</version>
<scope>compile</scope>
</dependency>
三、常见JUnit4和JUnit5的区别以及常用注解
原文链接:https://blog.csdn.net/winteroak/article/details/80591598
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。 |
四、assertEquals()和assertTrue()
相同之处:都能判断两个值是否相等
assertTrue 如果为true,则运行success,反之Failure
assertEquals 如果预期值与真实值相等,则运行success,反之Failure
不同之处:
assertEquals 运行Failure会有错误提示,提示预期值是xxx,而实际值是xxx。容易调式
assertTrue 没有错误提示、
assertEquals(期望值,实际值);
assertTrue(boolean类型值);
assertEquals("1A2B",secret.compare(5346));
assertTrue(secret >= 1000 && secret <= 9999);
五、常见问题
当出现Intellij IDEA junit 5使用之org.junit.jupiter不存在
解决 :在@Test注解 Add"JUnit 5.2"to classpath(鼠标点击注解@Test 左边出现红色灯泡,点击)