JUnit 教程

JUnit 教程

原文: https://howtodoinjava.com/junit-4/

JUnit 是 Java 编程语言的单元测试框架。 JUnit 在测试驱动开发的开发中很重要,并且是一系列单元测试框架之一。 它的主要用途是为您的应用代码单元编写可重复的测试。

安装

要将 JUnit 包含到您的项目中,您需要将其依赖项包含在类路径中。

  • JUnit Maven 依赖项

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
    
    
  • JUnit Gradle 依赖项

dependencies {
  testCompile 'junit:junit:4.12'
}

JUnit 注解

JUnit 提供以下注解来编写测试。

注解 描述
@Before 带注解的方法将在测试类中的每个测试方法之前运行。
@After 带注解的方法将在测试类中的每个测试方法之后运行。
@BeforeClass 带注解的方法将在测试类中的所有测试方法之前运行。 此方法必须是静态的。
@AfterClass 带注解的方法将在测试类中的所有测试方法之后运行。 此方法必须是静态的。
@Test 用于将方法标记为 junit 测试
@Ignore 它用于禁用或忽略测试套件中的测试类或方法。
@FixMethodOrder 此类允许用户选择测试类中方法的执行顺序。
@Rule 注解引用规则的字段或返回规则的方法。
@ClassRule 注解引用规则的静态字段或返回它们的方法。

用 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 测试套件,您可以运行分散到多个测试类中的测试。 在 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 {   
}  

断言

断言有助于通过测试用例的实际输出来验证期望的输出。 所有的断言都在org.junit.Assert类中。 所有的断言方法都是static,它使代码可读性更好。

import static org.junit.Assert.*;

@Test
public void method() {
	assertTrue(new ArrayList().isEmpty());
}

假设

假设表明测试有意义的条件。 失败的假设并不意味着代码已损坏,但是测试没有提供有用的信息。 假设基本上是指“如果这些条件不适用,请勿运行此测试”。 默认的 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 是 Java 技术中使用最多且功能最强大的单元测试框架。 它具有易于学习的曲线,并且易于遵循编码实践。 大多数 IDE 都内置了对 IDE 自身内部 junit 测试执行的支持,这使其对开发人员更加友好。

参考:

JUnit 文档