解决testng断言跳出问题
****TestNG提供了很多断言方法 大部分断言失败后会报exception而终止进程,在实际的测试中这样的做法是不可行的
如何做到断言失败不中断执行
创建监听器
package testng;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import org.testng.ITestResult;
import org.testng.TestListenerAdapter;
public class AssertListener extends TestListenerAdapter {
@Override
public void onTestStart(ITestResult result) {
Assertion.flag = true;
Assertion.errors.clear();
}
@Override
public void onTestFailure(ITestResult tr) {
this.handleAssertion(tr);
}
@Override
public void onTestSkipped(ITestResult tr) {
this.handleAssertion(tr);
}
@Override
public void onTestSuccess(ITestResult tr) {
this.handleAssertion(tr);
}
private int index = 0;
private void handleAssertion(ITestResult tr){
if(!Assertion.flag){
Throwable throwable = tr.getThrowable();
if(throwable==null){
throwable = new Throwable();
}
StackTraceElement[] traces = throwable.getStackTrace();
StackTraceElement[] alltrace = new StackTraceElement[0];
CopyOnWriteArrayList<Error> currList = new CopyOnWriteArrayList<Error>(Assertion.errors);
for (Error e : currList) {
StackTraceElement[] errorTraces = e.getStackTrace();
StackTraceElement[] et = this.getKeyStackTrace(tr, errorTraces);
StackTraceElement[] message = new StackTraceElement[]{new StackTraceElement("message : "+e.getMessage()+" in method : ", tr.getMethod().getMethodName(), tr.getTestClass().getRealClass().getSimpleName(), index)};
index = 0;
alltrace = this.merge(alltrace, message);
alltrace = this.merge(alltrace, et);
}
if(traces!=null){
traces = this.getKeyStackTrace(tr, traces);
alltrace = this.merge(alltrace, traces);
}
throwable.setStackTrace(alltrace);
tr.setThrowable(throwable);
Assertion.flag = true;
Assertion.errors.clear();
tr.setStatus(ITestResult.FAILURE);
}
}
private StackTraceElement[] getKeyStackTrace(ITestResult tr, StackTraceElement[] stackTraceElements){
List<StackTraceElement> ets = new ArrayList<StackTraceElement>();
for (StackTraceElement stackTraceElement : stackTraceElements) {
if(stackTraceElement.getClassName().equals(tr.getTestClass().getName())){
ets.add(stackTraceElement);
index = stackTraceElement.getLineNumber();
}
}
StackTraceElement[] et = new StackTraceElement[ets.size()];
for (int i = 0; i < et.length; i++) {
et[i] = ets.get(i);
}
return et;
}
private StackTraceElement[] merge(StackTraceElement[] traces1, StackTraceElement[] traces2){
StackTraceElement[] ste = new StackTraceElement[traces1.length+traces2.length];
for (int i = 0; i < traces1.length; i++) {
ste[i] = traces1[i];
}
for (int i = 0; i < traces2.length; i++) {
ste[traces1.length+i] = traces2[i];
}
return ste;
}
}
重写断言方法
package testng;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import org.testng.Assert;
public class Assertion {
public static boolean flag = true;
public static List<Error> errors = new ArrayList<Error>();
public static void verifyEquals(Object actual, Object expected){
try{
Assert.assertEquals(actual, expected);
}catch(Error e){
errors.add(e);
flag = false;
}
}
public static void verifyEquals(Object actual, Object expected, String message){
try{
Assert.assertEquals(actual, expected, message);
}catch(Error e){
errors.add(e);
flag = false;
}
}
public static void verifyNulls(boolean actual, boolean expected){
try{
Assert.assertEquals(actual, expected);
}catch(Error e){
errors.add(e);
flag = false;
}
}
public static void verifyNulls(boolean actual, boolean expected , String msg){
try{
Assert.assertEquals(actual, expected, msg);
}catch(Error e){
errors.add(e);
flag = false;
}
}
public static void assertTrue(boolean condition, String message) {
try{
Assert.assertTrue(condition, message);
}catch(Error e){
errors.add(e);
flag = false;
}
}
//其他需要的断言方法都可以这样写进来.....
}
执行测试
package testng;
import static org.testng.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
import com.github.checkpoint.CheckPointUtils;
import com.github.checkpoint.JsonCheckResult;
import com.github.crab2died.ExcelUtils;
import com.github.crab2died.exceptions.Excel4JException;
import apitest.HttpClientUtils;
import apitest.MapUtils;
import apitest.ParamBean;
import apitest.ParamUtils;
import apitest.TestCase;
import apitest.TestResult;
import apitest.db.DbCheckUtils;
import apitest.thread.ApiThreadTest;
import io.qameta.allure.Epic;
import io.qameta.allure.Severity;
import io.qameta.allure.SeverityLevel;
import io.qameta.allure.Step;
import io.qameta.allure.Story;
@Listeners(AssertListener.class)
public class ApiTestNg {
String path = System.getProperty("user.dir") + File.separator + "data" + File.separator + "apitest11.xlsx";
private static final Logger logger = LoggerFactory.getLogger(ApiTestNg.class);
@BeforeClass
public void beforeClass() {
HttpClientUtils.openProxy = false;
}
// @AfterClass
// public void afterClass() {
// try {
// String path_result = System.getProperty("user.dir") + File.separator + "result" + File.separator;
// File result_file = new File(path_result);
// if (!result_file.exists()) {
// result_file.mkdirs();
// }
// String resultFile = path_result + "result_" + ApiThreadTest.getDate() + ".xlsx";
// ExcelUtils.getInstance().exportObjects2Excel(ApiThreadTest.listResult, TestResult.class, resultFile);
// System.out.println("测试发邮件");
//
// EmailUtils.sendEmailsWithAttachments("测试结果", "请查收测试结果", resultFile);
// } catch (Exception e) {
// e.printStackTrace();
// System.out.println("结果处理");
// logger.error("error {} {}", e, "测试");
// }
// }
@Epic("并行单元测试")//测试集
@Story("单元测试")//测试case
@Step("获取城市编码")//测试步骤
@Severity(SeverityLevel.CRITICAL)//设置case的优先级
@Test(dataProvider = "excelobject",threadPoolSize = 10)
public void testcase(ParamBean paramBean) {
System.out.println(Thread.currentThread().getName() + " " + paramBean);
List<TestResult> runTestResults = new ArrayList<TestResult>();
try {
// addmap
ParamUtils.addFromObject(paramBean);
// 读原始数据(上一组数据被改掉了)
List<TestCase> list = ExcelUtils.getInstance().readExcel2Objects(ApiThreadTest.path, TestCase.class);
for (TestCase testCase : list) {
if (testCase.isRun()) {
System.out.println("替换前--" + testCase);
// 参数替换
ApiThreadTest.params_replace(testCase);
// 函数支持
ApiThreadTest.funtion_replace(testCase);
System.out.println("替换后--" + testCase);
// 替换变量
String result = "";
if ("get".equals(testCase.getType())) {
result = HttpClientUtils.doGet(testCase.getUrl());
} else if ("post".equals(testCase.getType())) {
result = HttpClientUtils.doPost(testCase.getUrl(),
MapUtils.covertStringToMap1(testCase.getParams()));
} else if ("postjson".equals(testCase.getType())) {
result = HttpClientUtils.doPostJson(testCase.getUrl(), testCase.getParams(),
MapUtils.covertStringToMap2(testCase.getHeaders()));
}
String testReulst_str = CheckPointUtils.check(result, testCase.getCheckpoint()).getMsg();
JsonCheckResult jsonCheck = CheckPointUtils.check(result, testCase.getCheckpoint());
ParamUtils.addFromJson(result, testCase.getCorrelation());
// 数据检查
String dbcheckResult = DbCheckUtils.check(testCase.getDbcheckpoint());
// 结果处理
TestResult testResult = new TestResult();
testResult.setTestResult(testReulst_str);
testResult.setDbtestResult(dbcheckResult);
BeanUtils.copyProperties(testResult, testCase);
runTestResults.add(testResult);
//assertTrue(jsonCheck.isResult(),jsonCheck.getMsg());
Assertion.assertTrue(jsonCheck.isResult(),jsonCheck.getMsg());
}
}
} catch (Exception e) {
e.printStackTrace();
}finally {
System.out.println(" 当前结果----------------");
ParamUtils.clear();
ApiThreadTest.listResult.addAll(runTestResults);
runTestResults.clear();
}
}
@DataProvider(name = "excel", parallel = true)
public Iterator<Object[]> excelProvider() {
List<Object[]> dataProvider = new ArrayList<Object[]>();
// 参数数据
try {
List<ParamBean> params_list = ExcelUtils.getInstance().readExcel2Objects(path, ParamBean.class, 1);
for (ParamBean paramBean : params_list) {
dataProvider.add(new Object[] { paramBean });
}
} catch (InvalidFormatException | Excel4JException | IOException e) {
e.printStackTrace();
}
return dataProvider.iterator();
}
@DataProvider(name = "excelobject", parallel = true)
public Object[][] excelProviderObject() {
//List<Object[]> dataProvider = new ArrayList<Object[]>();
// 参数数据
Object[][] objects = null;
try {
List<ParamBean> params_list = ExcelUtils.getInstance().readExcel2Objects(path, ParamBean.class, 1);
objects=new Object[params_list.size()][1];
for (int i = 0; i < params_list.size(); i++) {
objects[i][0]=params_list.get(i);
}
} catch (InvalidFormatException | Excel4JException | IOException e) {
e.printStackTrace();
}
return objects;
}
}
作者:我是刘先生
地址:https://www.cnblogs.com/cekaigongchengshi/
文章转载请标明出处,如果,您认为阅读这篇博客让您有些收获,不妨点击一下推荐按钮,据说喜欢分享的,后来都成了大神
欢迎扫码关注微信公众号 |