繁体   English   中英

如何在一个子类中的不同方法中调用超类的几个对象?

[英]How can I call few objects of superclass inside different methods in one subclass?

我尝试在Java + Selenium WebDriver上编写自动化测试,该特定测试现在可以正常工作,但是在我看来,代码质量存在问题-最奇怪的行是这里的每个测试都调用超类的对象。

我试图通过删除测试方法内的所有对象调用并在类内添加一个对象调用来重构它,但是得到了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清晰代码的建议,请写。 我会非常感激。

非常感谢!

首先,我建议从页面对象中删除断言,它将在将来陷入困境。

rpvp.AssertRecoverPasswordValidationPage(); // no :^C

其次,我认为您无需过多地忽略变量名,当您开始进行复杂的测试场景时,很难理解它。 下面的代码:

ForgotPasswordPage fp = new ForgotPasswordPage(driver);

可以变成:

ForgotPasswordPage forgotPasswordPage = new ForgotPasswordPage(driver);

第三,如果您正在使用页面工厂,并且测试遵循一个顺序(我知道测试应该是独立的,但是在UI测试中几乎是梦),则可以在@BeforeTest部分实例化您的页面(请注意,您的@页面对象中的FindBy事物仅在您首次使用后才会被“定位”,因此在测试类上使用它之前不要介意创建它的方式,请检查有关@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();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM