Selenium和SpecFlow之间的共享方法

时间:2014-12-22 13:41:39

标签: c# design-patterns selenium bdd specflow

我有一个测试项目,它包含我想测试的所有Selenium场景,我想在这个解决方案中添加一个SpecFlow项目,显然会使用一些WebDriver方法。 我不想复制我的代码,但SpecFlow与Selenium不兼容(例如Selenium正在使用SpecFlow中不允许的[TestInitialize]属性)。 将两者结合起来的最佳方法是什么?

我想执行与“SomeTestMethod”相同的步骤,但使用SpecFlow。

这是该项目的一个例子:

public class SeleniumBaseTest : BaseTest
{
    [AssemblyInitialize]
    public static void Initialize(TestContext testContext)
    {
    }

    Public SomeMethod()
    {
    }
}
[TestClass]
public class SeleniumFeature : SeleniumBaseTest 
{
   [TestInitialize]
   public void SeleInitialize()
   {
   }

   [TestMethod]
   public void SomeTestMethod()
    {            
    }
}

2 个答案:

答案 0 :(得分:1)

由于SpecFlow步骤实际上只是继承自System.Object的类的公共方法,因此只需实例化步骤定义类并从Selenium测试中调用公共方法。

<强> DataSteps.cs

[Binding]
public class DataSteps
{
    [Given("Something exists in the database")]
    public void GivenSomethingExistsInTheDatabase()
    {
        // ...
    }
}

在Selenium测试课程中:

[TestClass]
public class SeleniumFeature : SeleniumBaseTest 
{
    private DataSteps dataSteps;

    [TestInitialize]
    public void SeleInitialize()
    {
        dataSteps = new DataSteps();
    }

    [TestMethod]
    public void SomeTestMethod()
    {
        dataSteps.GivenSomethingExistsInTheDatabase();
    }
}

唯一真正的痛苦是当您需要使用TechTalk.SpecFlow.Table对象作为步骤定义的参数时。要弄清楚该语法,请查看使用Gherkin表语法的.feature文件之一的Designer生成的源,例如

Scenario: Testing something important
    Given a Foo exists with the following attributes:
        | Field | Name  |
        | Name  | Foo   |
        | Fruit | Apple |

如果有帮助,您可以将步骤定义保存在自己的程序集中。

答案 1 :(得分:0)

你可以使用像钩子这样的属性:

[BeforeTestRun] [AfterTestRun]

[BeforeFeature] [AfterFeature]

[BeforeScenario]或[Before] [AfterScenario]或[After]

[BeforeScenarioBlock] [AfterScenarioBlock]

[BeforeStep] [AfterStep的]

有关挂钩的详细信息,请转到here