NUnit Specflow 如何为所有测试共享一个类实例 [英] NUnit Specflow how to share a class instance for all tests
问题描述
我将 Specflow 与 NUnit 和 Selenium 一起使用,并希望在所有测试中共享驱动程序实例.我可以使用 FeatureContext 做到这一点,但在所有测试中都看不到任何内容.我知道这可能不是正确的方法,但我想知道是否有办法.
I am using Specflow with NUnit and Selenium and want to share instance of driver across all tests. I can do do this up to feature level with FeatureContext but can't see anything for all tests. I am aware that this is probably not the right way to go but I want to know if there is a way.
请帮忙举例.
谢谢
推荐答案
有几种方法可以做到这一点.此页面
There are a few ways to do this. Most are covered on this page
我个人可能会做的是定义一个 SeleniumContext
类并在我所有的 Step 类构造函数中需要这个类,然后告诉 SpecFlow 的 IOC 在每个场景中使用相同的实例:
What I personally would probably do is define a SeleniumContext
class and require this class in all my Step class constructors, then tell SpecFlow's IOC to use the same instance in every scenario:
首先创建类来保存 selenium 驱动程序实例
First create the class to hold the selenium driver instance
public class SeleniumContext
{
public SeleniumContext()
{
//create the selenium context
WebDriver = new ...create the flavour of web driver you want
}
public IWebDriver WebDriver{get; private set;}
}
然后设置 IOC 每次返回相同的实例
then setup the IOC to return the same instance every time
[Binding]
public class BeforeAllTests
{
private readonly IObjectContainer objectContainer;
private static SeleniumContext seleniumContext ;
public BeforeAllTests(IObjectContainer container)
{
this.objectContainer = container;
}
[BeforeTestRun]
public static void RunBeforeAllTests()
{
seleniumContext = new SeleniumContext();
}
[BeforeScenario]
public void RunBeforeScenario()
{
objectContainer.RegisterInstanceAs<SeleniumContext>(seleniumContext );
}
}
然后确保您的步骤类始终在其构造函数中询问上下文(您需要在您拥有的每个步骤类中都这样做)
Then ensure your step classes always ask for the context in their constructors (you need to do this in every step class you have)
[Bindings]
public class MySteps
{
private SeleniumContext seleniumContext;
public MyClass(SeleniumContext seleniumContext)
{
//save the context so you can use it in your tests
this.seleniumContext = seleniumContext;
}
//then just use the seleniumContext.WebDriver in your tests
}
或者,如果您已经将实例存储在功能上下文中,那么您可以使用 BeforeFeature
钩子来保存相同的实例:
alternatively if you are already storing the instance in the feature context then you can just use the BeforeFeature
hook to save the same instance:
[Binding]
public class BeforeAllTests
{
private static WebDriver webDriver;
[BeforeTestRun]
public static void RunBeforeAllTests()
{
webDriver = new WebDriver();
}
[BeforeFeature]
public static void RunBeforeFeature()
{
FeatureContext["WebDriver"] = webDriver;
}
}
这篇关于NUnit Specflow 如何为所有测试共享一个类实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!