TestNG异常测试

基本使用

TestNG通过@Test(expectedExceptions) 来判断期待的异常,并且判断Error Message

例如:

public class ExceptionTest {

    @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "NullPoint")
    public void testException(){
        throw new IllegalArgumentException("NullPoint");
    }
}

实际案例

业务类:AppBlog.java

package me.yezhou;

public class AppBlog {
    private String message;

    public AppBlog(String message){
        this.message = message;
    }

    // prints the message
    public String printMessage(){
        System.out.println("AppBlog: printMessage");
        return message;
    }

    public void calculate() {
        System.out.println("AppBlog: calculate");
        int a = 0;
        int b = 1/a;
    }
}

测试类:AppBlogTest.java

package me.yezhou;

import org.testng.Assert;
import org.testng.annotations.Test;

public class AppBlogTest {
    String message = "AppBlog.CN";
    AppBlog appBlog = new AppBlog(message);

    @Test
    public void testPrintMessage() {
        System.out.println("Inside testPrintMessage()");
        Assert.assertEquals(message, appBlog.printMessage());
    }

    @Test(expectedExceptions = ArithmeticException.class)
    public void testCalculate() {
        System.out.println("Inside testCalculate()");
        appBlog.calculate();
    }
}

测试结果:

Inside testCalculate()
AppBlog: calculate
Inside testPrintMessage()
AppBlog: printMessage

===============================================
Suite
Total tests run: 2, Failures: 0, Skips: 0
===============================================
上一篇 TestNG忽略测试
下一篇 TestNG分组测试
目录
文章列表
1 Android Toolbar自定义菜单
Android Toolbar自定义菜单
2
Prometheus使用Consul实现自动服务发现
Prometheus使用Consul实现自动服务发现
3
Android Butterknife 采坑记录
Android Butterknife 采坑记录
4
Vue或React项目代码相同运行出错采坑记录
Vue或React项目代码相同运行出错采坑记录
5
Swift - 类和结构体的区别
Swift - 类和结构体的区别
最新评论
一位WordPress评论者
一位WordPress评论者
2月12日
您好,这是一条评论。若需要审核、编辑或删除评论,请访问仪表盘的评论界面。评论者头像来自 Gravatar。