【问题标题】:How does dependency injection work in Cucumber?依赖注入如何在 Cucumber 中工作?
【发布时间】:2017-12-23 02:16:32
【问题描述】:

我一直在尝试将webdriver 注入步骤中。我用过this instructions,效果很好。

这个想法是将 WebDriver 作为服务注入到步骤类中。在初始步骤中,您需要添加以下依赖项。

<dependency>
    <groupId>info.cukes</groupId>
    <artifactId>cucumber-spring</artifactId>
    <version>1.2.5</version>
    <scope>test</scope>
</dependency>

依赖注入涉及三个主要类。下面我们一一介绍。

基础工具

BaseUtil 是具有WebDriverof Selenium 属性的类。这个类很简单:

public class BaseUtil {

 private WebDriver driver;

 public WebDriver getDriver() {return driver;}

 public void setDriver(WebDriver driver) { this.driver = driver;}
}

挂钩

Hook 类包含@Before, @After。方法 testInitialier() 负责加载 webDriver 文件 并创建实例,方法 testTearDown() 负责关闭浏览器。

    public class Hook extends BaseUtil{

    BaseUtil base;


    @Before
    public void testInitializer(){
        File file = new 
            File(IgniteTaskApplication.class.getClassLoader().getResource("driver/chromedriver.exe").getFile());
        String driverPath=file.getAbsolutePath();
        System.out.println("Webdriver is in path: "+driverPath);
        System.setProperty("webdriver.chrome.driver",driverPath);
        base.setDriver(new ChromeDriver());
    }

    public Hook(BaseUtil base) {
        this.base = base;
    }

    @After
    public void tearDownTest(){
        base.getDriver().close();
    }
}

步骤

steps 类包含来自已编译特征文件的步骤。要在 Eclipse 中编译功能文件,您需要在 Eclipse 中安装 Eclipse-Cucumber 插件。

public class ClickButton_Steps extends BaseUtil{
    BaseUtil base;

    public ClickButton_Steps(BaseUtil base){
        super();
        this.base=base;
    }

    @When("^I clcik on the button$")
    public void i_clcik_on_the_button() throws Throwable {
        cb=new ClickButtonPage(base.getDriver());
        cb.navigator();
    }

        // The other steps ...
}

如何运行它?

打开功能文件 -> 运行方式 -> 使用 Junit 运行

问题

我想知道以什么方式运行方法会导致依赖注入?

我猜顺序如下:

  1. Junit 调用@Before 方法,即testInitializer()
  2. testInitializer()在 Hook 类中,所以它需要创建一个 Hook 类的实例。
  3. 导致调用 Hook 类的构造函数。

但是,我无法理解其余的步骤。甚至可能根本不是真的。我的意思是,我有一个功能代码,但我无法解释它是如何工作的?

【问题讨论】:

  • 顶行说明链接已损坏

标签: java selenium junit dependency-injection cucumber


【解决方案1】:

据我了解,您使用 JUnit 作为带有 cucumber-spring 的测试框架。 JUnit 提供以下生命周期。

当您使用注解 @Before 对方法进行注解时,它将在您拥有的每个测试之前调用此方法。 至于@After 可以用于清理资源并在每次测试后调用。

运行测试时的测试流程:

  • testInitializer
  • i_clcik_on_the_button
  • tearDownTest

此外,您可以使用日志记录 (slf4j) 代替 System.out.println,这样更容易跟踪测试流程。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-13
    • 1970-01-01
    • 1970-01-01
    • 2014-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多