在WatiN测试中维护单个对象

时间:2011-06-30 17:19:41

标签: c# design-patterns watin

我在NUnit测试中保持对象单例存在问题。

这是我的基类:

[TestFixture]
public class SuiteBase
{
    public MyLib lib = null;

    [TestFixtureSetUp]
    public void TestFixtureSetUp()
    {
        lib = MyLib.Instance;
    }

    [TestFixtureTearDown]
    public void TestFixtureTearDown()
    {
    }
}

这是我的测试套件之一。

[TestFixture]
public class Suite1 : SuiteBase
{
    [Test]
    public void Test1()
    {
        lib.Foo();
        //...
    }

    [Test]
    public void Test2()
    {
        lib.Bar();
        //...
    }
}

MyLib类定义如下:

//singleton class
public sealed class MyLib
{
    public IE browser;
    //other public fields...

    public static MyLib Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new MyLibLib();

                using (StreamWriter sw = new StreamWriter(@"c:\test.txt", true))
                {
                    sw.WriteLine("Creating object");
                    sw.Flush();
                }
            }

            return instance;
        }
    }

    private static MyLib instance;

    private MyLib()
    {
        browser = new IE();
        //init the rest of public fields
    }
}

问题是每次测试都会创建单例类对象,我使用:

运行
int result = NUnit.ConsoleRunner.Runner.Main(new string[] { 
"/run:" + MyAssembly.GetName().Name + testSuiteName + "." + testCaseName, MyAssembly.Location, 
                            "/process:Single",
                            "/domain:Single",
                            "/nothread",
                            "/timeout:" + testTimeout
        }
    );

任何想法都会受到赞赏。感谢。

1 个答案:

答案 0 :(得分:0)

将“/ domain:Single”更改为“/ domain:None”后,立即创建单个对象