TestNg @Test的expectedExceptionsMessageRegExp属性

本文将讨论TestNG中@Test 注解的expectedExceptionsMessageRegExp属性。

这个属性有什么作用?根据文档:

如果指定了expectedExceptions ,则其消息必须与此属性中指定的正则表达式匹配。

因此,这意味着如果不先使用expectedparameter,我们将无法使用此属性。请阅读这篇文章,了解更多关于expectedbacklist属性的信息。这里expectedExceptionsMessageRegExp将使用正则表达式(regex)来匹配抛出的异常消息。

import java.io.IOException;
import org.testng.annotations.Test;
 
public class CodekruTest {
 
    // matching an empty regex string
    @Test(expectedExceptions = { IOException.class, ArithmeticException.class }, expectedExceptionsMessageRegExp = "")
    public void test1() throws IOException {
        System.out.println("test1 throwing an IOException");
        throw new IOException("");
    }
 
    // matching exact regex
    @Test(expectedExceptions = { IOException.class,
            ArithmeticException.class }, expectedExceptionsMessageRegExp = "codekru")
    public void test2() throws IOException {
        System.out.println("test1 throwing an IOException");
        throw new IOException("codekru");
    }
 
    // this test will fail as message do not match the regex
    @Test(expectedExceptions = { IOException.class,
            ArithmeticException.class }, expectedExceptionsMessageRegExp = "bye")
    public void test3() throws IOException {
        System.out.println("test1 throwing an IOException");
        throw new IOException("codekru");
    }
 
    // here used regex to match the thrown exception message
    @Test(expectedExceptions = { IOException.class }, expectedExceptionsMessageRegExp = "^Hi .*$")
    public void test4() throws Exception {
        throw new IOException("Hi Codekru test");
    }
 
}

产出-

test1 throwing an IOException
test1 throwing an IOException
test1 throwing an IOException
PASSED: test1
PASSED: test2
PASSED: test4
FAILED: test3
org.testng.TestException: 
The exception was thrown with the wrong message: expected "bye" but got "codekru"
	at org.testng.internal.ExpectedExceptionsHolder.wrongException(ExpectedExceptionsHolder.java:71)

所以,这里test3()失败是因为抛出的异常消息与正则表达式不匹配,这就是我们在TestNG中使用expectedExceptionsMessageRegExp属性的方式。请访问此链接以了解有关常规异常符号的更多信息。

上一篇:Django中间件


下一篇:Guidebook