JUnit 注释
JUnit 提供以下注释来编写测试。
| Annotation | 描述 |
|---|---|
@Before | 带注释的方法将在测试类中的每个测试方法之前运行。 |
@After | 带注释的方法将在测试类中的每个测试方法之后运行。 |
@BeforeClass | 带注释的方法将在测试类中的所有测试方法之前运行。这个方法必须是静态的。 |
@AfterClass | 带注释的方法将在测试类中的所有测试方法之后运行。这个方法必须是静态的。 |
@Test | 它用于将方法标记为junit测试 |
@Ignore | 它用于禁用或者忽略测试套件中的测试类或者方法。 |
@FixMethodOrder | 此类允许用户选择测试类中方法的执行顺序。 |
@Rule | 注释引用规则或者返回规则的方法的字段。 |
@ClassRule | 注释引用规则或者返回它们的方法的静态字段。 |
on
it
road
.com
测试套件
使用 JUnit 测试套件,我们可以运行分布到多个测试类中的测试。
在 JUnit 中,@RunWith和 @Suite注释都用于运行套件测试。
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({
TestJunit1.class,
TestJunit2.class
})
public class JunitTestSuite {
}
在 JUnit 中编写测试
在 JUnit 中,测试方法用 @Test注释标记。
为了运行该方法,JUnit 首先构造该类的一个新实例,然后调用带注释的方法。
测试抛出的任何异常都会被 JUnit 报告为失败。
如果没有抛出异常,则假定测试成功。
import java.util.ArrayList;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
public class Example {
@BeforeClass
public static void setup() {
}
@Before
public void setupThis() {
}
@Test
public void method() {
org.junit.Assert.assertTrue(new ArrayList().isEmpty());
}
@After
public void tearThis() {
}
@AfterClass
public static void tear() {
}
}
JUnit 是 Java 编程语言的单元测试框架。
JUnit 在测试驱动开发的发展中一直很重要,并且是单元测试框架家族中的一员。
它的主要用途是为应用程序代码单元编写可重复的测试。
假设
假设表明测试有意义的条件。
失败的假设并不意味着代码被破坏,而是测试没有提供有用的信息。
假设基本上意味着“如果这些条件不适用,则不要运行此测试”。
默认的 JUnit 运行器会跳过假设失败的测试。
import org.junit.Test;
import static org.junit.Assume.*;
public class Example {
public class AppTest {
@Test
void testOnDev()
{
System.setProperty("ENV", "DEV");
assumeTrue("DEV".equals(System.getProperty("ENV")));
}
@Test
void testOnProd()
{
System.setProperty("ENV", "PROD");
assumeFalse("DEV".equals(System.getProperty("ENV")));
}
}
}
安装
要将 JUnit 包含到项目中,我们需要将其依赖项包含到类路径中。
- JUnit Maven 依赖
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
- JUnit Gradle 依赖
dependencies {
testCompile 'junit:junit:4.12'
}
- JUnit Jar 文件
单击链接下载 JUnit 4.12 jar 文件。
断言
断言有助于使用测试用例的实际输出来验证预期输出。
所有断言都在 org.junit.Assert 类中。
所有断言方法都是 static,它使代码可读性更好。
import static org.junit.Assert.*;
@Test
public void method() {
assertTrue(new ArrayList().isEmpty());
}
日期:2020-09-17 00:10:52 来源:oir作者:oir
