java如何只对一种测试方法执行AfterMethod
我必须在我的代码中使用Test
方法,我只想为一个方法执行AfterMehtod
。有人知道怎么做吗
这是我的代码:
package Demo;
import java.util.concurrent.TimeUnit;
import library.Utility;
import org.openqa.selenium.By;
import org.testng.ITestResult;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
import Pages.custom_actions_page;
import com.relevantcodes.extentreports.ExtentReports;
import com.relevantcodes.extentreports.ExtentTest;
import com.relevantcodes.extentreports.LogStatus;
public class Custom_Actions extends start {
ExtentReports report;
ExtentTest logger;
String driverPath = "D:\\geckodriver-v0.16.1-win64\\geckodriver.exe";
@Test()
public void signin() throws Exception {
// To Locate the Username field
driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
driver.findElement(By.id("username")).sendKeys("admin");
// To locate the Password field
driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
driver.findElement(By.id("password")).sendKeys("admin123");
// Click on Login button
driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
driver.findElement(By.id("submit")).click();
}
@Test(dependsOnMethods = { "signin" })
public void create_custom_action() {
report = new ExtentReports("D:/Reports/Report.html");
logger = report.startTest("Create Custom Action");
new custom_actions_page(driver).submit();
new custom_actions_page(driver).admin();
new custom_actions_page(driver).custom_ac();
new custom_actions_page(driver).createnew();
new custom_actions_page(driver).nameAs("fortesting").descriptionAs(
"description");
new custom_actions_page(driver).category();
new custom_actions_page(driver).assetsubtype();
new custom_actions_page(driver).assettype();
new custom_actions_page(driver).flintnameAs("hello:example.rb");
new custom_actions_page(driver).submit_butto();
new custom_actions_page(driver).Save_Button();
logger.log(LogStatus.PASS, "Custom Action Created Successfully");
}
@AfterMethod()
public void tearDown(ITestResult result) {
// Here will compare if test is failing then only it will enter into if
// condition
if (ITestResult.FAILURE == result.getStatus()) {
try {
Utility.captureScreenshot(driver, "CustomActionFail.png");
} catch (Exception e) {
System.out.println("Exception while taking screenshot "
+ e.getMessage());
}
}
report.endTest(logger);
report.flush();
driver.close();
}}
# 1 楼答案
@AfterMethod
的设计目的是,当您需要在每次测试后执行相同的代码块,而不必在每次测试中重复代码块时,您的生活会更轻松。因此,如果只需要在一次测试之后执行,只需将其嵌入@Test
方法中,并删除@AfterMethod
注释的方法# 2 楼答案
有几种方法可以使用TestNG中的
Native Injection
来实现。有关TestNG中本机注入的可能组合的更多详细信息,请参阅here最简单的方法是从
@AfterMethod
注释的方法中检查即将执行的@Test
方法的名称,如果它与需要特殊执行的方法的名称匹配,则继续执行,否则跳过执行@AfterMethod
。 但这是一种原始的方法,因为如果您将测试方法的名称重构为其他名称,您的方法就会被破坏另一种方法是基本上使用标记接口,并执行与上述相同的逻辑
下面是一个例子,展示了所有这些都在起作用
标记注释如下所示
现在,您的测试类将如下所示
请注意,我们如何仅为方法
testMethod1()
添加注释@NeedsSpecialSetup
,以指示我们只需要为testMethod1()
执行@AfterMethod
这是输出