gpt4 book ai didi

java - TestNG预期异常处理: Have my cake as well as eat it?

转载 作者:行者123 更新时间:2023-12-02 06:19:52 26 4
gpt4 key购买 nike

如何处理 TestNG 中的预期异常,以便无论测试方法中的代码是否抛出异常,测试都会通过

我有 testng 测试方法,它创建某些对象的列表。在 for 循环中,针对每个对象执行特定操作。此操作可能会也可能不会引发异常。如何使用@Test(expectedExceptions)使得无论是否抛出异常,总体测试结果都是通过的。根据我的理解,expectedExceptions 总是会寻找异常。如果发现异常,则由 Testng 处理,测试结果通过。如果未找到异常或抛出不同的异常,则测试失败

public class DemoException {
@Test(expectedExceptions = {ConnectException.class})
public void testException() throws ConnectException
{
//pseudo code......
//create a List<WebElement> myList
int count = 0;
for(WebElemet we: myList){
we.connect(); //this may or may not throw exception
we.getResponseMessage(); // further actions on we is needed
we.disconnect();
//above 3 are HttpURLConnection methods to be precise
// Basically do - connect, getResponse, disconnect

System.out.println(count++);
// print count is needed - exception thrown or not thrown
}
}
}

预期:无论是否抛出异常,测试方法都应该通过。即使抛出异常,也应该打印计数值

实际结果:测试方法通过(抛出异常)但未打印计数值。如果添加任何 try-catch 逻辑,则会打印计数值,但测试方法会失败。这不是我想要的。

最佳答案

你为什么不试试这个:

@Test(expectedExceptions = Exception.class)
public void MyTest() throws Exception {
int count = 0;
try {
for (int i = 0; i < 10; i++) {

throw new Exception("Fake Exception");
}
}
catch (Exception ex)
{
System.out.println(count++);
throw ex;
}
}

将计数打印到日志/控制台,然后再次抛出异常。

关于java - TestNG预期异常处理: Have my cake as well as eat it?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55842876/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com