testng实现verify断言

来源:互联网 发布:商务通弹窗js代码 编辑:程序博客网 时间:2024/06/06 20:03

1.构造一个Verify类,将testNg的Assert断言异常捕获,利用监听器在@Test方法结束后一次性抛出


2.编写Verify类,可按需求扩充

package com.p;import org.testng.Assert;public class Verify {public static StringBuffer verificationErrors= new StringBuffer();;public static void verifyTrue(boolean o) {try {Assert.assertTrue(o);} catch (Error e) {verificationErrors.append(e.toString());}}public static void verifyFalse(boolean o) {try {Assert.assertFalse(o);} catch (Error e) {verificationErrors.append(e.toString());}}public static void verifyEquals(Object expected, Object actuals) {try {Assert.assertEquals(expected, actuals);} catch (Error e) {verificationErrors.append(e.toString());}}public static void verifyEquals(Object expected, Object actuals,String message) {try {Assert.assertEquals(expected, actuals, message);} catch (Error e) {verificationErrors.append(e.toString());}}public static  void assertEquals(String actual, String expected,String message) {try {Assert.assertEquals( actual, expected, message);} catch (Error e) {verificationErrors.append(e.toString());}}public static  void assertEquals(String actual, String expected) {try {Assert.assertEquals( actual, expected);} catch (Error e) {verificationErrors.append(e.toString());}}public static void tearDown() {String verificationErrorString = verificationErrors.toString();if (!"".equals(verificationErrorString)) {Assert.fail(verificationErrorString);}}}
3.实现监听器,使用IInvokedMethodListener

(开始用的是IHookable,但这个最近不知道什么原因不能用了,囧,只能换成IInvokedMethodListener)

package com.p;import org.testng.IInvokedMethod;import org.testng.IInvokedMethodListener;import org.testng.ITestResult;public class ListenerVerify implements IInvokedMethodListener {@Overridepublic void afterInvocation(IInvokedMethod method, ITestResult testResult) {// TODO Auto-generated method stubif (method.isTestMethod()) {Verify.tearDown();}}@Overridepublic void beforeInvocation(IInvokedMethod method, ITestResult testResult) {// TODO Auto-generated method stub}}

4.再写测试类验证下,在测试类中添加上写好的监听器

@Listeners( {com.p.ListenerVerify.class})public class w  {boolean a = true;@Testpublic void a(){System.out.println("@Testaaaaaa");Verify.assertEquals("1", "2");Verify.assertEquals("1", "3");}}



0 0