【问题标题】:How to initialize an instance variable (declared in a test fixture in nunit) every time before each test method(contained in the same test fixture)? [duplicate]每次在每个测试方法(包含在同一个测试夹具中)之前,如何初始化一个实例变量(在 nunit 的测试夹具中声明)? [复制]
【发布时间】:2018-11-02 20:45:09
【问题描述】:

我在 vs2015 的同一个测试夹具下有 3 个 nunit 测试用例。当我单独运行测试用例时,它们通过了。但是当我一起运行它们时,第一个测试用例通过了,其他的都失败了。

因为我有一个实例变量,即 testfixture 中的一个 c# 属性,它在第一个测试用例执行之前被初始化。这仅在第一个测试用例运行之前被初始化,我希望在每个测试用例开始之前初始化这个属性。但是正在发生的事情是——它在第一个测试用例运行之前被初始化,第二个和第三个测试用例使用相同的值。因此我的第二个和第三个测试用例失败了。

我该怎么做?

在下面的代码中 - Page 是 c# 属性 - 执行登录,登录后单击相应的链接并带您到目标页面。

这是代码,

[TestFixture]
public class SecurityUserMgmtTests
{
    private SecurityUserManagementPage _page;
    protected override SecurityUserManagementPage Page
    {
        get
        {
            if (_page == null)
            {
                _page = new LoginPage().LoginasAdmin().GoToSecurityUserMgmtPage();
            }

            return _page;
        }
    }

    [Test]
    public void Test_ChooseARole()
    {
        Page.ChooseSecurityRole("administrator", "NMD");

    }

    [Test]
    public void Validate_if_submitting_form_without_securityrole_results_in_alertpopup()
    {
        Page.FillinLoginDetails("testuserr9", "2018/10/06", "yassds", "Ardaa");
        Page.ClickSubmit();
        var alertText = alert.Text;
        alert.Dismiss();

        Assert.AreEqual("Please select a Role for this user", alertText);
    }


    [Test]
    public void Validate_if_creating_adminuser_with_existing_username_results_in_css_alert()
    {
        Page.ChooseSecurityRole("NMD");
        Page.FillinLoginDetails("iatestuser", "2018-05-01", "yas", "Ara");
        Page.ClickSubmit();

        Assert.IsTrue(Page.GetErrorMessage().Contains("already exists"));
    }

}

【问题讨论】:

  • @him brombeere 它不是重复的。让我编辑问题。
  • 好吧,answer of Sumeshk 告诉你该怎么做。

标签: c# selenium-webdriver nunit pageobjects


【解决方案1】:

使用 NUnit,您可以使用 SetUp attribute 定义一个方法,该方法将在测试夹具中的每个测试运行一次。由于您的 Page 属性可能需要为每次运行设置,您可以使用以下内容:

[TestFixture]
public class SecurityUserMgmtTests
{

    protected override SecurityUserManagementPage Page {get;set;}

    [SetUp]
    public void Init() => Page = new LoginPage().LoginasAdmin().GoToSecurityUserMgmtPage();

    // Tests omitted
}

【讨论】:

  • 非常感谢。它让我发疯了,现在它起作用了。在您回答之前,我一直认为不能超过 1 个 [Setup] 属性。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-28
  • 2019-06-01
  • 2018-11-22
  • 2014-03-17
  • 2017-02-15
相关资源
最近更新 更多