我是Selenium的新手,使用testNG框架。 以下是我试图理解的代码
@Test
public void softAssertionTest() {
try{
softAssert.assertTrue(name.equals("HardAssertionTest"));
softAssert.assertEquals(1, 1,"Error 1");
softAssert.assertEquals("a","b","Error ab");
System.out.println("Line after assertions");
} catch (Throwable t){
System.out.println("+++++++++++");
verificationErrors.append(t);
System.out.println("Verification error - method1"+ verificationErrors);
}
}
@Test
public void softAssertionTest2() {
softAssert.assertTrue(name.equals("HardAssertionTest"));
softAssert.assertEquals(3, 4,"Error 3,4");
softAssert.assertEquals("c","d","Error cd");
System.out.println("Line after assertions method 2");
}
@AfterTest
public void afterTest(){
softAssert.assertAll();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
System.out.println(verificationErrorString);
}
}
问题 1)我读到在配置方法中进行断言不是一个好习惯。而是在每个测试方法中执行它们。因此,我修改代码如下
@Test
public void softAssertionTest() {
try{
softAssert.assertTrue(name.equals("HardAssertionTest"));
softAssert.assertEquals(1, 1,"Error 1");
softAssert.assertEquals("a","b","Error ab");
System.out.println("Line after assertions");
doSoftAssert();
} catch (Throwable t){
System.out.println("+++++++++++");
verificationErrors.append(t);
System.out.println("Verification error - method1"+ verificationErrors);
}
}
@Test
public void softAssertionTest2() {
try{
softAssert.assertTrue(name.equals("HardAssertionTest"));
softAssert.assertEquals(3, 4,"Error 3,4");
softAssert.assertEquals("c","d","Error cd");
System.out.println("Line after assertions method 2");
doSoftAssert();
} catch (Throwable t){
System.out.println("+++++++++++");
verificationErrors.append(t);
System.out.println("Verification error - method2"+ verificationErrors);
}
}
public void doSoftAssert(){
softAssert.assertAll();
/*String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
System.out.println(verificationErrorString);
}*/
}
当我运行它时,我看到从softAssertionTest2()
调用softAssert.assertAll()
也执行了softAssertionTest1()
中的断言,复制了断言。如何只能断言一次断言?
问题 2)将错误附加到verificationErrorString
是正确的方式还是建议将这些错误添加到HashMap
中?
如何只能断言一次断言?
每个测试都应实例化自己的SoftAssert
对象,并且不应在多个@Test
方法之间共享。
将错误附加到
verificationErrorString
是正确的方式,还是建议将这些错误添加到HashMap
中?
你永远不应该用try..catch
块包装你的断言,因为它会导致你吞噬异常,并且它会在你的测试中添加大量的样板代码。如果你的意图基本上是捕获验证消息,那么你应该查看子类化org.testng.asserts.SoftAssert
,其中你:
- 覆盖
org.testng.asserts.Assertion#onAssertSuccess
(如果要捕获传递的断言)和 - 覆盖
org.testng.asserts.Assertion#onAssertFailure(org.testng.asserts.IAssert<?>, java.lang.AssertionError)
(如果要捕获失败的断言)