我面临的挑战是,我使用MSTest测试框架有许多数据驱动的测试方法。这些数据驱动方法中的每一个都使用相同的测试数据来实例化对象。我不想在每个单一测试方法中实例化同一对象,而不是用相同的数据驱动每个单一测试方法的数据,我想对该类使用一次该测试数据,并为每个单一测试方法实例化该对象。但是我不确定这是否可能吗?
以下是我如何使用NUnit执行所需行为的示例:
namespace Web.Tests.BestPractices
{
[TestFixture]
[TestFixtureSource(typeof(CrossBrowserData), "LatestConfigurations")]
[Parallelizable]
public class LoginFeature : BaseTest
{
private SauceDemoLoginPage _loginPage;
public LoginFeature(string browser, string version, string os) :
base(browser, version, os)
{
}
[Test]
public void LoginPageShouldLoad()
{
_loginPage.Open().IsLoaded.Should().BeTrue("the login page should load successfully.");
}
最终,[TestFixtureSource(typeof(CrossBrowserData), "LatestConfigurations")]
指向一个包含我所有测试数据的类。此数据用于驱动每个测试方法,如下所示:
[TestFixture]
public class BaseTest
{
[SetUp]
public void ExecuteBeforeEveryTestMethod()
{
var sauceConfig = new SauceLabsCapabilities {IsDebuggingEnabled = true};
SauceLabsCapabilities.BuildName = _sauceBuildName;
Driver = new WebDriverFactory(sauceConfig).CreateSauceDriver(_browser, _browserVersion, _osPlatform);
SauceReporter = new SauceJavaScriptExecutor(Driver);
SauceReporter.SetTestName(TestContext.CurrentContext.Test.Name);
SauceReporter.SetBuildName("BestPracticesTests5");
_isUsingSauceLabs = true;
}
private readonly string _browser;
private readonly string _browserVersion;
private readonly string _osPlatform;
public BaseTest(string browser, string browserVersion, string osPlatform)
{
_browser = browser;
_browserVersion = browserVersion;
_osPlatform = osPlatform;
}
结果,我有一堆测试方法,这些方法针对传递给BaseTest.cs构造函数public BaseTest(string browser, string browserVersion, string osPlatform)
我无法在MSTest中模拟同一件事,因为[DynamicData]
似乎仅适用于方法级别。
此外,另一个挑战是,我需要在[TestInitialize]中实例化该对象Driver = new WebDriverFactory(sauceConfig).CreateSauceDriver(_browser, _browserVersion, _osPlatform);
,这与在NUnit中的操作类似:
public class BaseTest
{
[SetUp]
public void ExecuteBeforeEveryTestMethod()
{
Driver = new WebDriverFactory(sauceConfig).CreateSauceDriver(_browser, _browserVersion, _osPlatform);
//other unimportant code...
}
但是所有测试数据似乎只能在[TestMethod]
级别输入。因此,看来我以前不可能做[TestInitialize]
吗?
现在看来,实现这一目标的唯一方法就是这样做吗?还是有更有效的方法?
[TestMethod]
[DynamicData("LatestConfigurations", typeof(MsTestCrossBrowserData),
DynamicDataDisplayName = "GetCustomDynamicDataDisplayName",
DynamicDataDisplayNameDeclaringType = typeof(MsTestCrossBrowserData))]
public void SeleniumTest1(string browser, string version, string osVersion)
{
Driver = new WebDriverFactory(sauceConfig).CreateSauceDriver(_browser, _browserVersion, _osPlatform);
SimpleTest(MethodBase.GetCurrentMethod().Name);
}