我尝试在 Java + Selenium WebDriver 上编写自动化测试,这个特定的测试现在可以正常工作,但在我看来,代码质量存在问题 - 最奇怪的行是为这里的每个测试调用父类(super class)的对象.
我尝试通过删除测试方法内的所有对象调用并在类内添加一个对象调用来重构它,但得到了 NullPointerException。
@BeforeTest
public void initialize() throws IOException{
driver = initializeDriver();
}
@Test
public void sendRecoverEmailValid() {
ForgotPasswordPage fp = new ForgotPasswordPage(driver);
fp.AssertForgotPasswordPage();
fp.setRecoverEmail(validRecoveryEmail);
fp.pressSendButton();
RecoverPasswordValidationPage rpvp = new RecoverPasswordValidationPage(driver);
rpvp.AssertRecoverPasswordValidationPage();
}
@Test
public void sendRecoverEmailInvalid() {
ForgotPasswordPage fp = new ForgotPasswordPage(driver);
fp.AssertForgotPasswordPage();
fp.setRecoverEmail(invalidRecoveryEmail);
fp.pressSendButton();
fp.AssertRecoverEmailErrorPresece();
}
@AfterTest
public void shutdown() {
shutdownDriver();
}
那么,该如何解决呢? 也许您对 java/selenium 的清晰代码有任何其他建议,请写下来。我将非常感激。
非常感谢!
最佳答案
首先,我建议从页面对象中删除断言,它将来会变成 hell 。
rpvp.AssertRecoverPasswordValidationPage(); // no :^C
第二,我认为您不需要过多地省略变量名称,当您开始执行复杂的测试场景时,它真的很难阅读。下面这段代码:
ForgotPasswordPage fp = new ForgotPasswordPage(driver);
可以变成:
ForgotPasswordPage forgotPasswordPage = new ForgotPasswordPage(driver);
第三,如果您正在使用页面工厂并且您的测试将遵循一个顺序(我知道测试应该是独立的,但在 UI 测试中这几乎是一个梦想),您可以在@BeforeTest 部分(请记住,页面对象的 @FindBy 内容仅在您第一次使用它之后才会“定位”,因此不要介意在测试类 check this answer about @FindBy 上使用之前创建它)。下面这段代码:
@BeforeTest
public void initialize() throws IOException{
driver = initializeDriver();
}
将变成:
// in case you are using JUnit, this attributes should be static, don't remember about TestNG. (Nullpointer situation)
private ForgotPasswordPage forgotPasswdPage;
private RecoverPasswordValidationPage recoverPasswdValidationPage;
@BeforeTest
public void initialize() throws IOException{
driver = initializeDriver();
forgotPasswdPage = new ForgotPasswordPage(driver);
recoverPasswdValidationPage = new RecoverPasswordValidationPage(driver);
}
我建议您不要将下面的代码移动到父类(保持现在的样子),因为如果您计划将来在类级别并行运行,你可能会看到奇怪的事情发生,因为你的测试类共享同一个父类,当我们开始转向并行时,我遇到了超过 50 个类的问题,你的测试类应该控制何时启动和结束 WebDriver。
@BeforeTest
public void initialize() throws IOException{
driver = initializeDriver();
}
@AfterTest
public void shutdown() {
shutdownDriver();
}
关于java - 如何在一个子类的不同方法中调用父类(super class)的几个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57616324/