当前位置: java基础教程 > 16-junit > 阅读正文

org.junit.Test

2021.5.1.   3834 次   688字

junit 是用于快速测试的工具,能够提高测试效率

1.把 junit 的 jar 包导入到项目中

如果没有 jar 包,点击这里下载(junit.4.1.2.jar 和 hamcrest-core-1.3.jar)

  • 使用 eclipse,点击 build path , 把 junit 导入到 library 中
  • 使用 idea 时,根目录新建一个lib目录,把jar包复制进去,点击add as library

maven坐标如下:

<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>
2.使用步骤

新建一个测试类,导入类

import org.junit.Test;

接着,写上任意方法,在每个方法上加上 @Test 注解

此时,任意方法均可独立运行,在 idea 中点击左边执行,eclipse 直接run

3.测试代码规范

一般都会新建一个 Test 包,专门用来写测试文件

对于测试的类文件,不要写 Test.java,否则与 org.junit.Test 重名

对于测试方法,最好是空参空返回值

可以使用断言的多种重载方法,判断结果是否与真实的相符

Assert.assertEquals(判断的结果,实际的结果)
4.@before 和 @after

@before 修饰的方法,会在任意测试方法被执行前,自动执行

@after 修饰的方法,会在任意测试方法被执行后,自动执行

本篇完,还有疑问?

加入QQ交流群:11500065636 IT 技术交流群