TestNG中如何跳过指定测试方法并在测试报告中标记为已跳过
TestNG测试用例标记为跳过状态的正确实现方式
SkipException不生效的常见原因
- 导入了错误的SkipException类,确认导入的是
org.testng.SkipException,而非其他第三方包中的同名类 - 代码中的try-catch块捕获了Exception类型异常,将SkipException吞掉,没有向外抛出
- throw语句放在了测试方法所有业务逻辑执行完成之后,中间逻辑提前抛出了其他异常导致SkipException没有被执行到
正确实现代码
方案1:执行完所有方法逻辑后标记为跳过
直接在方法最后一行抛出SkipException即可,注意不要捕获该异常:
import org.testng.SkipException; // 注意导入正确的类 @Test(priority = 18, dataProvider="excelSheetNameAsMethodName",dataProviderClass=ExcelDataProvider.class) public void addNotesFromRequisitionListAndDetailsPage(String username,String emailID,String password) throws Exception { cbatLoginPage().enterEmailID(emailID, password); cbatMyAccountPage().verifyApplicantTrackingTile(); cbatMyAccountPage().selectTile("Applicant Tracking"); cbatHomePage().switchWindow(); cbatHomePage().verifyCBATHomePage(username); cbatHomePage().selectWidget("MY REQUISITIONS"); cbatRequisitionPage().clickFirstNoteIcon(); String noteText = "Test Note "+ RandomGenerator.GenerateRandomNumber(3); cbatRequisitionPage().enterNewNote(noteText); cbatRequisitionPage().clickFirstNoteIcon(); cbatRequisitionPage().verifyNoteAdded(noteText); cbatRequisitionPage().selectRequisition(); cbatRequisitionPage().clickFilledNoteIcon(); noteText = "Test Note "+ RandomGenerator.GenerateRandomNumber(3); cbatRequisitionPage().enterNewNote(noteText); cbatRequisitionPage().clickFilledNoteIcon(); cbatRequisitionPage().verifyNoteAdded(noteText); // 最后抛出SkipException,TestNG会自动将该用例标记为跳过状态 throw new SkipException("自定义跳过说明信息"); }
如果你的代码中包含捕获全局Exception的逻辑,需要单独处理SkipException,避免被吞:
@Test(priority = 18, dataProvider="excelSheetNameAsMethodName",dataProviderClass=ExcelDataProvider.class) public void addNotesFromRequisitionListAndDetailsPage(String username,String emailID,String password) throws Exception { try { // 你的所有业务逻辑代码 // ... throw new SkipException("自定义跳过说明信息"); } catch (SkipException se) { // 直接抛出不处理 throw se; } catch (Exception e) { // 其他异常的处理逻辑 e.printStackTrace(); } }
方案2:不需要执行任何逻辑直接跳过
如果不需要运行测试方法的任何代码,直接标记为跳过,可以直接给@Test注解添加enabled = false属性:
@Test(enabled = false, priority = 18, dataProvider="excelSheetNameAsMethodName",dataProviderClass=ExcelDataProvider.class) public void addNotesFromRequisitionListAndDetailsPage(String username,String emailID,String password) throws Exception { // 方法内代码不会执行,测试报告直接标记为跳过 // ... }
内容的提问来源于stack exchange,提问作者ankush singh
相关产品推荐
相关产品推荐

