Java-TestNG:在catch块中使用testngassert.fail()是否错误
我在catch块中遇到了一个由带有Java-TestNG:在catch块中使用testngassert.fail()是否错误,java,selenium-webdriver,testng,assert,Java,Selenium Webdriver,Testng,Assert,我在catch块中遇到了一个由带有Assert.fail(“某些文本”)的人编写的代码。这是我的代码: try { //WebDriver code here which interacts with WebElements //When an exception occurs in this try block, it will be caught in //the catch and further catch block has Assert.fail() } catch (
Assert.fail(“某些文本”)
的人编写的代码。这是我的代码:
try {
//WebDriver code here which interacts with WebElements
//When an exception occurs in this try block, it will be caught in
//the catch and further catch block has Assert.fail()
} catch (Exception e) {
Assert.fail("failed to click 'Webelement' ");
}
不知怎么的,我觉得这样做是不对的。我错了吗
注意:不完全是的副本,因为我不希望有任何例外。如果出现任何异常,我需要使测试用例失败,尽管它在语法上并不错误。但是您最好将测试的措辞改为使用,并对引发的异常进行详细说明。例如: 如果使用
“test”
作为参数调用您的方法fromTest()
,可能会引发NumberFormatException
,则此类行为的测试定义应为:
@Test(expectedExceptions = NumberFormatException.class)
public void testMethod() {
System.out.println("About to throw an exception!");
fromTest("test");
}
注意:如果您认为异常可能发生在测试执行本身中,而不是从中调用任何其他方法。我建议不要抓住它。让它失效,然后你将修复它。可能的副本不是的副本,因为我不希望有任何例外。如果出现任何异常,我需要使测试用例失败。这里更糟糕的做法是抑制实际的异常(其消息和堆栈跟踪可能包含对测试失败的洞察),并用您自己的异常替换它。只需声明测试用例
抛出异常
,并让测试框架处理它。感谢您的快速响应。据我所知,“expectedException”将允许我的测试在测试中发生异常时通过。但我不希望我的测试抛出任何异常,如果出现任何异常,我的测试应该失败。因此,据我所知,我的测试方法不应该有任何try-catch块,如果发生异常,我应该让TestNG处理它(并且TestNG没有通过测试-这应该很好)@user2048204,但我不希望我的测试抛出任何异常,如果发生任何异常,我的测试应该失败。。。。如果您的测试导致意外的异常,您实际上不应该捕获它。相反,修复它或者让您正在使用的框架决定如何处理它。