引言:
JUnit 是一个回归测试框架,被开发者用于实施对应用程序的单元测试,加快程序编制速度,同时提高编码的质量。
JUnit 是 Java 的一个框架,所以最根本的需要是在你的机器里装有 JDK。
JUnit 测试框架使用时要考虑两个方面:
1. Case设计执行的前置条件
2. 确定case的执行顺序
JUnit的基本注解:
JUnit API: https://junit.org/junit4/javadoc/latest/index.html
@BeforeClass //execute only once, in the starting
@AfterClass //execute only once, in the end
@Before //execute for each test, before executing test
@After //execute for each test, after executing test
@Test注解提供2个参数:
- expected
- timeout
@Ignore
JUnit 测试顺序:
Junit 4.11里增加了指定测试方法执行顺序的特性,测试类的执行顺序可通过对测试类添加注解 @FixMethodOrder(value)
来指定,其中value 为执行顺序 ,下面是value值下对应的测试顺序行为:
- MethodSorters.DEFAULT (默认)
- MethodSorters.NAME_ASCENDING (推荐), 字典顺序
- MethodSorters.JVM
example code:
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class TaskTest {.....
}
Assert:
在测试中结果中关于Failure和error的解释
1.Failure 一般由测试单元使用断言方法判断失败引起的,这个报错,说明测试点发现了问题,即程序输出的结果和我们预期的不一样
2.error 是由代码异常引起的,它可以产生代码本身的错误,也可以是测试代码中的一个隐藏bug