我们使用TestNG侦听器功能在外部工具中报告测试结果。它工作正常。
但是现在,我们想要添加单例(ThreadLocal webdriver)包含的信息。我们的测试活动是并行运行的,因此我们有多个单例实例。
我们如何在onSuccess方法中获取正确的单例,从而报告正确的信息?
编辑:代码示例
public class QTestWrapper implements ISuiteListener, ITestListener {
...
@Override
public void onTestSuccess(ITestResult result) {
String sessionId = MyDriver.getSessionId();
// do my job with this session id
}
...
}
public final class MyDriver {
private static final ThreadLocal<MyDriver> MY_DRIVER =
ThreadLocal.withInitial(MyDriver::buildDriver);
private WebDriver driver;
private MyDriver(WebDriver driver) {
this.driver = driver;
}
public static MyDriver getDriver() {
return MY_DRIVER.get();
}
private static MyDriver buildDriver() {
URL remoteAddress = getHubAddress();
DesiredCapabilities caps = buildCapabilities();
WebDriver driver = new RemoteWebDriver(remoteAddress, caps);
return new MyDriver(driver);
}
public static String getSessionId() {
String sessionId = null;
MyDriver driver = MY_DRIVER.get();
if (driver != null && driver.getWrappedDriver() != null) {
WebDriver wrappedDriver = driver.getWrappedDriver();
sessionId = ((RemoteWebDriver) wrappedDriver).getSessionId().toString();
}
return sessionId;
}
public WebDriver getWrappedDriver() {
return driver;
}
}
public class TestLogin {
@AfterMethod(alwaysRun = true)
public void die() {
StickyDriver.quit();
}
@Test(description = "Check that a user can login with a Manager profile.")
public void loginAsManager() {
Actor actor = new Actor("foo");
String userName = actor.openBrowserAndLogin().getUserName();
assertThat(userName).isEqualTo("foo");
}
}
public class Actor {
private static final Logger LOGGER = LogManager.getLogger();
private final MyDriver driver;
private User user;
public Actor(String userName) {
user = User.getUser(userName);
driver = MyDriver.getDriver();
}
public Actor(User user) {
this.user = Objects.requireNonNull(user);
driver = MyDriver.getDriver();
}
public HomePage openBrowserAndLogin() {
openBrowser();
return login();
}
public HomePage login() {
LoginPage loginPage = new LoginPage(driver);
loginPage.getUserNameField().setValue(user.getUsername());
loginPage.getPasswordField().setValue(user.getPassword());
return loginPage.login();
}
private void openBrowser() {
String url = EnvironmentHelper.getUrl();
WebDriver webDriver = driver.getWrappedDriver();
webDriver.get(url);
try {
new WebDriverWait(webDriver, 60).until(AjaxExpectedConditions.callsHaveCompleted());
} catch (TimeoutException ex) {
closeBrowser();
throw ex;
}
}
public void closeBrowser() {
MyDriver.quit();
}
}
答案 0 :(得分:1)
TestNG不保证@Test
和onSuccess()
将在同一个帖子中执行。
只有在使用org.testng.IInvokedMethodListener
实施时才会提供此保证。
因此,请更改您的实施以执行以下操作:
QTestWrapper
实施org.testng.IInvokedMethodListener
afterInvocation()
org.testng.IInvokedMethodListener
内检查执行的方法是否为@Test
方法,并且其状态是否为通过,如果通过,则移动您的逻辑onSuccess()
1}}进入它。