【问题标题】:static classes instances + integration tests静态类实例 + 集成测试
【发布时间】:2013-06-03 12:19:57
【问题描述】:

我创建了一个 nunit 测试项目,其中包含 5 个不同的 TestFixture 中的许多集成测试。我有一个名为ConfigSettings 的类,它具有[SetupFixture] 属性和一个具有[SetUp] 属性的方法,它基本上连接到数据库以检索设置。检索到的设置应在整个测试中使用。 5 个不同的 TestFixture 都继承自这个类ConfigSettings。

我注意到每次测试都会运行SetupFixture [setup] 方法,所以我使用了一个标志'HasRun'来避免这种情况。但是,当 TestFixture1 准备好并且运行器转到 TestFixture2 时,HasRun 将再次为 0,因为将创建一个新实例。我怎样才能让 SetupFixture 属性类在 TestSuite 的开头只运行一次?一种解决方案是将HasRun 属性和所有其他属性设为静态,但是如果我随后打开一个新的 NUnit 实例,则这些属性将具有与第一个实例相同的值。请问有什么想法吗?

问题基本上是静态类的第二个实例仍然会检索第一个实例的属性值,如果我用新设置覆盖它们,第一个实例将使用第二个实例的值。这种行为有什么解决方法吗?

这是我正在尝试做的示例代码:

下面是 SetupFixture 类,它应该在项目开始时在任何其他 testfixture 之前运行:-

[SetUpFixture]
public class ConfigSettings
{
    private static string strConnectionString = @"connectionStringHere";

    public string userName { get; set; }
    public string userId { get; set; }
    public int clientId { get; set; }
    public int isLive { get; set; }
    public int HasRun { get; set; }

    [SetUp]
    public void GetSettings()
    {
        if (HasRun != 1)
        {
            Console.WriteLine("executing setup fixture..");
            HasRun = 1;
            using (var db = new autodb(strConnectionString))
            {
                var currentSession = (from session in db.CurrentSessions
                                      where session.TestSuiteID == 1
                                      orderby session.TestStarted descending
                                      select session).FirstOrDefault();

                userId = currentSession.UserId.ToString();
                clientId = currentSession.ClientID;
                isLive = currentSession.IsLive;

                etc...
            }
        }
    }
}

现在我从每个 TestFixture 继承 ConfigSettings 类并访问它的属性,例如:-

[TestFixture]
public class TestFixture1: ConfigSettings
{
    [Test]
    public void Test1()
    {
        Console.WriteLine("executing test 1...");
        Console.WriteLine(userId);
    }

    [Test]
    public void Test2()
    {
        Console.WriteLine("executing test 2...");
        Console.WriteLine(clientId);
    }
}

谢谢。

【问题讨论】:

  • 听起来您可能误用了这些属性。请向我们展示您正在使用的代码。
  • 你为什么用 NUnit 做集成测试?
  • 您可能需要方法上的 FixtureSetup 属性,而不是 SetupFixture 类。
  • nunit 中没有 FixtureSetup,但是有 TestFixtureSetup,它在新 TestFixture 的开头运行。相应添加了代码示例

标签: c# .net class static nunit


【解决方案1】:

如您所知,SetUp 只运行一次,SetupFixture 在测试前运行每个尖齿。

所以要回答您的问题. How can I have the SetupFixture attribute class run only once at the beginning of the TestSuite?,最简单的方法是使用SetUp 而不是SetupFixture

【讨论】:

  • Yes 具有 Setup 属性的方法将在每次测试之前运行。但是,我需要的是一种在每个 testfixture 之前运行的方法,就像项目的入口点一样,它检索设置,然后所有类都可以继承这些设置。我将发布一些代码,以便您可以清楚地看到图片
猜你喜欢
  • 1970-01-01
  • 2023-04-01
  • 2020-09-29
  • 2019-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-23
相关资源
最近更新 更多