JUnit单元测试

简介

JUnit是一个开源的java语言的单元测试框架
专门针对java语言设计, 使用最普遍, JUnit是标准的单元测试架构
java单元测试是最小的功能单元测试代码, 单元测试就是针对单个java方法的测试
 

目的

  • 确保单个方法正常运行
  • 测试代码能够做为示例代码
  • 能够自动化运行全部测试并得到报告
 

Maven依赖

<dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
</dependency>
 

项目结构


 

断言

在 JDK 1.4 以后,Java 中增长了断言的功能,关键字assert
 
断言是java的一种语句,它容许对程序提出一个判断(假设)。断言包含一个布尔表达式,在程序运行中它应该是真。假设程序指望获得某个结果,若是没达成则报错。断言用于确保程序的正确性,避免逻辑错误。
 
与异常处理相似,断言不能代替正常的检验,只是检测内部的一致性和有效性。断言在运行是检验,能够在程序启动时打开或关闭。
 
PS:不要在正常的业务逻辑中使用断言。对于程序正确性的判断能够在测试环境使用断言,生成环境则能够关闭该功能。
 
指望以外的结果:
import org.junit.Assert; /** * @author wzm * @version 1.0.0 * @date 2020/1/24 15:25 **/
public class MyTest { private static void test(int x) { int c = 10 + 20; int a = 12 * 100 / x; Assert.assertTrue("expected a == c ,but a != c", a == c); System.out.println("a == c"); } public static void main(String[] args) { int x = 10; test(x); } }

 

报错以下:java

 

指望的结果:
import org.junit.Assert; /** * @author wzm * @version 1.0.0 * @date 2020/1/24 15:25 **/
public class MyTest { private static void test(int x) { int c = 10 + 20; int a = 12 * 100 / x; Assert.assertTrue("expected a == c ,but a != c", a == c); System.out.println("a == c"); } public static void main(String[] args) { int x = 40; test(x); } }

运行结果:数据库

 

断言还有不少其余方法。
assertTrue
 
assertFalse
 
assertEquals
 
assertNotEquals
 
assertArrayEquals
 
...

 

开启断言

 

 

 

在VM options中输入-ea开启断言功能
 

junit注解

@Before:初始化测试资源
@After:释放测试资源
@BeforeClass: 初始化很是耗时的资源, 例如建立数据库
@AfterClass: 清理@BeforeClass建立的资源, 例如数据库资源
@Test:执行测试的主体
 

执行顺序

import org.junit.*; public class MyTestTest { public MyTestTest() { System.out.println("--new MyTestTest()"); } @BeforeClass public static void setUpBeforeClass() { System.out.println("--BeforeClass()"); } @AfterClass public static void tearDownAfterClass() { System.out.println("--AfterClass()"); } @Before public void setUp() { System.out.println("--Before()"); } @After public void tearDown() { System.out.println("--After()"); } @Test public void testA() { System.out.println("--testA()"); } @Test public void testB() { System.out.println("--testB()"); } @Test public void testC() { System.out.println("--testC()"); } }

 

运行整个类,执行结果:
 

 

 

运行单个测试testA:
 
 

超时测试

@Test(timeout=1000)能够设置超时时间
timeout单位是毫秒
@Test(timeout = 1000) public void testA() { System.out.println("--testA()"); }

 

异常测试

异常测试能够经过@Test(expected=Exception.class), 对可能发生的每种类型的异常进行测试
  • 若是抛出了指定类型的异常, 测试成功
  • 若是没有抛出指定类型的异常, 或者抛出的异常类型不对, 测试失败
 
运行以下代码: 正常经过,证实 确实发生了ArithmeticException异常
@Test(expected = ArithmeticException.class)   public void testException() {   int i = 1 / 0; }

 

运行以下代码: 有报错信息,表明没有报错或者报的是其余的错误。
@Test(expected = ArithmeticException.class)   public void testException() {   int i = 1 / 1; }
 
执行结果以下:
java.lang.AssertionError: Expected exception: java.lang.ArithmeticException
相关文章
相关标签/搜索