我是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);
}
}
Q1)我认为在配置方法中进行断言不是一个好习惯。而是在每种测试方法中做它们。因此,我修改代码如下
@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);
}*/
}
当我运行它时,我看到来自softAssert.assertAll()
的{{1}}调用也执行softAssertionTest2()
中的断言,复制断言。如何断言只能断言一次?
Q2)是否以正确的方式将错误追加到softAssertionTest1()
,还是建议在verificationErrorString
中添加这些错误?
答案 0 :(得分:1)
如何断言只断言一次?
每个测试都应该实例化自己的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)
(如果要捕获失败的断言)