静态类实例+集成测试

时间:2013-06-03 12:19:57

标签: c# .net class static nunit

我创建了一个nunit测试项目,在5个不同的TestFixtures中进行了大量的集成测试。我有一个名为ConfigSettings的类,它具有[SetupFixture]属性和一个[SetUp]属性的方法,它基本上连接到数据库以检索设置。检索到的设置应该在整个测试过程中使用。 5个不同的TestFixtures都继承自此类ConfigSettings

我注意到每个测试都运行SetupFixture [setup]方法,因此我使用了一个标记“HasRun”来避免这种情况。但是,当TestFixture1准备好并且跑步者转到TestFixture2时,HasRun将再次为0,因为将创建一个新实例。如何在TestSuite开头只运行一次SetupFixture属性类?解决方案是将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);
    }
}

感谢。

1 个答案:

答案 0 :(得分:0)

正如您所知,SetUp只运行一次而SetupFixture每次都会在测试前运行。

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