(四)JUnit 注解

虫师 创建于 over 6 years 之前

最后更新: about 1 month 之前

阅读数: 1

(四)JUnit 注解

JUnit 注解


JUnit 注解说明:

注解 说明
@Test: 标识一条测试用例。 (A) (expected=XXEception.class)   (B) (timeout=xxx)
@Ignore:  忽略的测试用例。
@Before:  每一个测试方法之前运行。
@After :  每一个测试方法之后运行。
@BefreClass  所有测试开始之前运行。
@AfterClass  所有测试结果之后运行。

例子


创建被测试类 Count .

public class Count {

    /**
     * 计算并返回两个参数的和
     */
    public int add(int x ,int y){
        return x + y;
    }

    /**
     * 计算并返回两个数相除的结果
     */
    public int division(int a, int b){
        return a / b;
    }
}

创建测试类 CountTest .

import static org.junit.Assert.assertEquals;

import org.junit.Ignore;
import org.junit.Test;


public class CountTest {

    //验证超时
    @Test(timeout=100)
    public void testAdd() throws InterruptedException {
        Thread.sleep(101);
        new Count().add(1, 1);
    }

    //验证抛出异常
    @Test(expected=ArithmeticException.class)
    public void testDivision() {
        new Count().division(8, 0);
    }

    // 跳过该条用例
    @Ignore
    @Test
    public void testAdd2() {
        Count count = new Count();
        int result = count.add(2,2);
        assertEquals(result, 5);
    }

}

1、在 testAdd() 用例中设置 timeout=100 , 说明的用例的运行时间不能超过 100 毫秒, 但故意在用例添加 sleep() 方法休眠 101 毫秒,所以会导致用例失败。

2、在 Java 中被除数不能为0,所以 8/0 会报 ArithmeticException 异常, 在 @Test 中设置 expected=ArithmeticException.class ,说明抛该异常符合预期。

3、@Ignore 表来标识该用例跳过,不管用例运行成功还是失败。

执行结果如下:

0

相关课程

webium简明教程
图文
webium简明教程

课程分类: 测试框架

开箱即用的page object模式

  • 已完结
  • 已更新8集
  • 最后更新时间: 2024-03-18 12:48:12

免费

查看详情
TestNG教程
图文
TestNG教程

课程分类: 测试框架

Java语言中最流行的测试框架了

  • 已完结
  • 已更新12集
  • 最后更新时间: 2024-03-18 12:55:14

免费

查看详情
python unittest测试框架教程
图文
python unittest测试框架教程

课程分类: 测试框架

python 自带的单元测试框架

  • 已完结
  • 已更新8集
  • 最后更新时间: 2024-03-18 12:12:46

免费

查看详情
TDD测试驱动开发教程
图文
TDD测试驱动开发教程

课程分类: 测试框架 软件测试基础

TDD其实并不神秘

  • 已完结
  • 已更新7集
  • 最后更新时间: 2024-03-18 11:53:22

免费

查看详情