java - 有没有比使用单个类更好的方法来提供辅助方法来测试 Web 应用程序?

标签 java unit-testing generics inheritance

我正在 JUnit 中使用 Selenium 为 Web 应用程序设计 UI 测试。我有一个基本测试类,其中包含类似的内容,我从中继承了我的测试:

public class BaseTest {

    protected TestSteps test;

    protected Assertions assertion;

    // set everything up...

}

然后测试看起来就像这样:

public class TestX extends BaseTest {

    @Test
    public testFeature1() {
        test.clickSomething().enterSomething(); // method chaining
        assertion.assertSomething();

        //...
    }

}

我遇到的问题:网络应用程序中有不同的模块,并且 Assertions/TestSteps仅适用于一个模块的方法使 Assertions/TestSteps 的界面变得困惑其他模块的类。

因此我尝试将断言/测试步骤分开。 问题是,方法链接返回 TestSteps 的实例。当然,当我有Module1TestSteps时使用方法doSomethingSpecific()那么我期望test.clickSomething().doSomethingSpecific()工作,但事实并非如此,因为clickSomething()将返回 TestSteps实例,而不是 Module1TestSteps实例。

我通过创建 AbstractTestSteps<T extends AbstractTestSteps<T> 来“解决”这个问题类(包含所有基本 TestSteps 方法)protected abstract T getThis();

然后我像这样扩展这个类:

public class BaseTestSteps extends AbstractTestSteps<BaseTestSteps> {

    // Constructors

    protected BaseTestSteps getThis() {
        return this;
    }

    // that's it, the "base methods" are all inherited from AbstractTestSteps...

}

对于基本测试步骤和

public class Module1TestSteps extends AbstractTestSteps<Module1TestSteps> {

    // same constructors...

    protected Module1TestSteps getThis() {
        return this;
    }

    public Module1TestSteps doSomeThingSpecific() {
        // do something

        return getThis();
    }

}

对于我的专业TestSteps 。目前它可以工作,但我不喜欢它,因为以下原因:

  • 所有通用方法都在 AbstractTestSteps 中类,但它们是通过 BaseTestSteps 的实例使用的
  • 如果我有 Module1 的子模块怎么办? ?我无法继承 Module1TestSteps ,仅来自 AbstractTestSteps。
  • 当我的一位同事尝试添加新的 TestSteps 时,我认为理解这些类的关系并不简单。类。

如何才能做得更好?

最佳答案

使用Page Object pattern 。也就是说,为每个页面创建一个 API,以便您的测试以描述用户体验的方式描述页面导航和交互。

它有一些好处可以解决您的担忧:

  • 它使用组合,而不是继承
  • 对于维护测试的人员来说很容易理解和解释,因为测试读起来就像对使用该应用程序的人的描述

关于java - 有没有比使用单个类更好的方法来提供辅助方法来测试 Web 应用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18146227/

相关文章:

java - 在 Eclipse RCP 中显示 View 时传递参数

java - 在一份 testNG 报告中显示多个测试套件的所有失败测试

generics - 接口(interface)的嵌套泛型类型

java - 什么是泛型 < 的真实例子? super T>?

java - 使用 Spring MVC 为 @RequestBody 使用泛型类型时出现 "argument type mismatch"错误

java - JLabels(和其他东西)不会显示在 JFrame(多个 JFrame)的 JPanel 内

java - 在使用 Mockito 进行方法调用时拦截对象

java - 列表 foreach 方法

java - 将一个测试资源移动到 Maven 中磁盘上的某个位置

python - 加速 Django 测试