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
===============================================

版权声明:
作者:Joe.Ye
链接:https://www.appblog.cn/index.php/2023/03/01/testng-abnormal-test/
来源:APP全栈技术分享
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
打赏
海报
TestNG异常测试
基本使用 TestNG通过@Test(expectedExceptions) 来判断期待的异常,并且判断Error Message 例如: public class ExceptionTest { @Test(expectedExcepti……
<<上一篇
下一篇>>
文章目录
关闭
目 录