以下内容引自: https://howtodoinjava.com/testng/testng-expected-exception-and-expected-message-tutorial/

Home  >  TestNG  >  TestNG – Expected Exception and Expected Message Tutorial

TestNG – Expected Exception and Expected Message Tutorial

November 20, 2014 by Lokesh Gupta

While writing unit tests there can be certain scenarios where we need to verify that an exception is being thrown by the program during execution. TestNG provides a feature to test such scenarios by allowing the user to specify the type of exceptions that are expected to be thrown by a test methodduring execution. It supports multiple values being provided for verification. If the exception thrown by the test is not part of the user entered list, the test method will be marked as failed.

Let’s create a sample test and learn how exception test works in TestNG.

@Test ( expectedExceptions = { IOException.class, NullPointerException.class } )

Let’s see an example to understand it better.

Example of Expected Exception Test

In below test, we have two test methods i.e. exceptionTestOne() and exceptionTestTwo(). Here exceptionTestOne() throws IOException where as exceptionTestTwo() throws Exception. The expected exception to validate while running these tests is mentioned using the expectedExceptions attribute value while using the Test annotation.

public class ExceptionTestDemo
{
    @Test(expectedExceptions = { IOException.class })
    public void exceptionTestOne() throws Exception {
        throw new IOException();
    }
 
    @Test(expectedExceptions = { IOException.class, NullPointerException.class })
    public void exceptionTestTwo() throws Exception {
        throw new Exception();
    }
}

Output of above test run is given below:

[TestNG] Running: C:\Users\somepath\testng-customsuite.xml
 
PASSED: exceptionTestOne
FAILED: exceptionTestTwo
 
org.testng.TestException:
Expected exception java.io.IOException but got org.testng.TestException:
Expected exception java.io.IOException but got java.lang.Exception
    at org.testng.internal.Invoker.handleInvocationResults(Invoker.java:1497)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1245)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:127)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:111)
    at org.testng.TestRunner.privateRun(TestRunner.java:767)
    at org.testng.TestRunner.run(TestRunner.java:617)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:334)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:329)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:291)
    at org.testng.SuiteRunner.run(SuiteRunner.java:240)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1224)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1149)
    at org.testng.TestNG.run(TestNG.java:1057)
    at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:111)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:204)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:175)
Caused by: org.testng.TestException:
Expected exception java.io.IOException but got java.lang.Exception
    at org.testng.internal.Invoker.handleInvocationResults(Invoker.java:1497)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:754)
    at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:901)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1231)
    ... 16 more
Caused by: java.lang.Exception
    at com.howtodoinjava.test.ExceptionTestDemo.exceptionTestTwo(ExceptionTestDemo.java:16)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:84)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:714)
    ... 18 more
 
===============================================
    Default test
    Tests run: 2, Failures: 1, Skips: 0
===============================================

As you can see from the test results, exceptionTestTwo() was marked as failed by TestNG during execution. The test failed because the exception thrown by the said method does not match the exception list provided in the expectedExceptions list.

Example of Expected Exception Test with Verifying Message

You can also verify a test based on the exception message that was thrown by the test. Regular expression can also be used to verify the error message, this can be done using .*. Depending upon the position of the regular expression we can use it to do pattern matching such as starts-with, contains, and ends-with while verifying the exception message.

Let’s learn how to write a exception test based on the exception message thrown.

public class ExceptionTestDemo
{
    @Test(expectedExceptions = { IOException.class }, expectedExceptionsMessageRegExp = "Pass Message test")
    public void exceptionTestOne() throws Exception {
        throw new IOException("Pass Message test");
    }
 
    @Test(expectedExceptions = { IOException.class }, expectedExceptionsMessageRegExp = ".* Message .*")
    public void exceptionTestTwo() throws Exception {
        throw new IOException("Pass Message test");
    }
 
    @Test(expectedExceptions = { IOException.class }, expectedExceptionsMessageRegExp = "Pass Message test")
    public void exceptionTestThree() throws Exception {
        throw new IOException("Fail Message test");
    }
}

Output of above test run is given below:

[TestNG] Running: C:\Users\somepath\testng-customsuite.xml
 
PASSED: exceptionTestOne
PASSED: exceptionTestTwo
FAILED: exceptionTestThree
 
org.testng.TestException:
Expected exception java.io.IOException but got org.testng.TestException:
The exception was thrown with the wrong message: expected "Pass Message test" but got "Fail Message test"
    at org.testng.internal.Invoker.handleInvocationResults(Invoker.java:1497)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1245)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:127)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:111)
    at org.testng.TestRunner.privateRun(TestRunner.java:767)
    at org.testng.TestRunner.run(TestRunner.java:617)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:334)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:329)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:291)
    at org.testng.SuiteRunner.run(SuiteRunner.java:240)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1224)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1149)
    at org.testng.TestNG.run(TestNG.java:1057)
    at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:111)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:204)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:175)
Caused by: org.testng.TestException:
The exception was thrown with the wrong message: expected "Pass Message test" but got "Fail Message test"
    at org.testng.internal.Invoker.handleInvocationResults(Invoker.java:1481)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:754)
    at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:901)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1231)
    ... 16 more
Caused by: java.io.IOException: Fail Message test
    at com.howtodoinjava.test.ExceptionTestDemo.exceptionTestThree(ExceptionTestDemo.java:21)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:84)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:714)
    ... 18 more
 
 
===============================================
    Default test
    Tests run: 3, Failures: 1, Skips: 0
===============================================

In above test methods exceptionTestThree() failed because expected message didn’t matched.

TestNG exception的更多相关文章

  1. selenium+testNG+Ant

    好几天没写了,抽时间写下,也好有个总结: 1.selenium+testNG+Ant (1)ant 是构建工具 他的作用就是运行你配置好的东西 而tentng.xml你可以认为他是管理test的一个配 ...

  2. Java Unit Testing - JUnit & TestNG

    转自https://www3.ntu.edu.sg/home/ehchua/programming/java/JavaUnitTesting.html yet another insignifican ...

  3. Exception in thread "main" java.lang.NoSuchMethodError: org.testng.TestNG.configure(Lorg/testng/CommandLineArgs;)V

    TestNG运行时报以下错误: Exception in thread "main" java.lang.NoSuchMethodError: org.testng.TestNG. ...

  4. testng 失败自动截图

    testng执行case failed ,testng Listener会捕获执行失败,如果要实现失败自动截图,需要重写Listener的onTestFailure方法 那么首先新建一个Listene ...

  5. TestNG 与 Junit的比较

    转自 http://www.blogjava.net/fanscial/archive/2005/12/14/23780.html 1.         JDK 5 Annotations (JDK ...

  6. APP接口自动化测试JAVA+TestNG(三)之HTTP接口测试实例

    前言     前两篇普及相关基础知识后,本篇主要对举例对国家气象局接口自动化测试进行讲解(Get请求及结果断言),以达到自动化测试入门目的,除了前两篇的一些了解外,需要有一定的JAVA知识(HTTP相 ...

  7. TestNG BeforeClass BeforeMethod Test AfterClass AfterMethod

    http://topmanopensource.iteye.com/blog/1983729 1.TestNG测试注解和Junit注解的不同以及生命周期: TestNG测试的一个方法的生命周期: @B ...

  8. 基于WebDriver&TestNG 实现自己的Annotation @TakeScreenshotOnFailure

    相信用过Selenium WebDriver 的朋友都应该知道如何使用WebDriver API实现Take Screenshot的功能. 在这篇文章里,我主要来介绍对failed tests实现 t ...

  9. testNg vs junit 4.X @Test

    http://www.ibm.com/developerworks/cn/java/j-cq08296/ 一个简单的测试用例 初看起来,JUnit 4 和 TestNG 中实现的测试非常相似.为了更好 ...

随机推荐

  1. obj-c在Xcode之外如何使用@import关键字

    在Xcode中@import可以很方便的代替#import的功能,具体区别和便利请自行google之. 这里简单介绍下在Xcode之外如何使用@import.直接以 @import Foundatio ...

  2. ios的位置和方向(来自苹果官方文档,仅供简单参考)

    取得用户的当前位置 Core Location框架使您可以定位设备的当前位置,并将这个信息应用到程序中.该框架利用设备内置的硬件,在已有信号的基础上通过三角测量得到固定位置,然后将它报告给您的代码.在 ...

  3. LeetCode之旅(21)-Swap Nodes in Pairs

    题目: Given a linked list, swap every two adjacent nodes and return its head. For example, Given 1-> ...

  4. rails中link_to与button_to的一个功能差异

    页面中本来设计一个按钮,功能是当按下时跳转到index方法,然后实现一段功能.关键是其中需要传递一个参数show_all,其值为true. index方法中通过判断是否含有该参数来实现不同的逻辑,类似 ...

  5. IOS空数据页面,网络加载失败以及重新登陆View的封装(不需要继承)

    一.问题 对于B2C和B2B项目的开发者,可能会有一个订单列表为空,或者其他收藏页面为空,用户token失效,判断用户要重新登陆,以及后台服务错误等提示.本篇课文,看完大约10分钟. 原本自己不想写空 ...

  6. java虚拟机的类加载机制

    引言 我们写的代码是放在.java文件中,经过编译器编译后,转成.class文件.Class文件是一串二进制流,它可以被各平台的虚拟机所接受,实现跨平台.      虚拟机将描述类的数据从class文 ...

  7. balanced binary tree(判断是否是平衡二叉树)

    Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced binary ...

  8. [Domino]Java访问Domino必需配置的服务器设置

    应用场景 我们需要通过Java远程访问IBM Lotus Domino R6和R5服务器,从中获取用户邮箱的邮件信息等关键数据.我们不需要提供每一个用户密码以及ID文件. 我们的具体做法是,通过Dom ...

  9. Django代码注意

    1.模板标签里面 extend和include是冲突的,有了extend,include无法生效,原因:是底层渲染独立机制设计导致. 2.#coding:utf-8 这句只有放在代码文件第一行才能生效 ...

  10. 《Linux下FTP服务器搭建及FTP使用》

    .LOGAndy:mxtd114 <Linux下FTP服务器搭建> 0.root登录 1.安装ftp # yum -y install ftp 2.安装vsftpd # yum -y in ...