Java - TestNG:在 catch 块中使用 testng Assert.fail() 是否错误
Java - TestNG : Is It Wrong to use testng Assert.fail() in a catch block
我在 catch 块中遇到了 Assert.fail("some text")
的人编写的代码。这是我的代码:
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' ");
}
不知何故我觉得这不是正确的做法。我错了吗?
注意:不完全是 Is Assert.Fail() considered bad practice 的副本,因为我不期待任何异常。如果发生任何异常,我需要使测试用例失败
虽然它在语法上并没有错。但是您最好改用 expectedException
代替您的测试,并具体说明抛出的异常。例如:
如果您的方法 fromTest()
在以 "test"
作为参数调用时可能抛出 NumberFormatException
,那么您对此类行为的测试定义应为:
@Test(expectedExceptions = NumberFormatException.class)
public void testMethod() {
System.out.println("About to throw an exception!");
fromTest("test");
}
注意:如果您认为异常可能发生在您的测试执行本身而不是从它调用任何其他方法.我建议不要抓住它。让它失败,然后你会修复它。
我在 catch 块中遇到了 Assert.fail("some text")
的人编写的代码。这是我的代码:
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' ");
}
不知何故我觉得这不是正确的做法。我错了吗?
注意:不完全是 Is Assert.Fail() considered bad practice 的副本,因为我不期待任何异常。如果发生任何异常,我需要使测试用例失败
虽然它在语法上并没有错。但是您最好改用 expectedException
代替您的测试,并具体说明抛出的异常。例如:
如果您的方法 fromTest()
在以 "test"
作为参数调用时可能抛出 NumberFormatException
,那么您对此类行为的测试定义应为:
@Test(expectedExceptions = NumberFormatException.class)
public void testMethod() {
System.out.println("About to throw an exception!");
fromTest("test");
}
注意:如果您认为异常可能发生在您的测试执行本身而不是从它调用任何其他方法.我建议不要抓住它。让它失败,然后你会修复它。