Search code examples
c#watinxunitresource-cleanup

xUnit and Watin cleanup


I have some test cases using xUnit and Watin. To make all Facts in the class share the same instance of IE, I had created a singleton class so the first test will launch a new IE instance, and the following tests will use the same instance.

After all Facts finish, the IE instance is still running. I just wonder how to close IE after all tests in the class finish.


Solution

  • For this purpose your class with tests need to implement IUserFixture<T> interface.
    I'll provide the example which solves your needs and demonstrates xunit life-cycle model:

    public class MyTestClass : IUseFixture<WatinFixture>, IDisposable
    {
        private WatinFixture _data;
    
        public void SetFixture(WatinFixture data)
        {
            _data = data;
            Console.WriteLine("setting data for test");
        }
    
        public MyTestClass()
        {
            Console.WriteLine("in constructor of MyTestClass");
        }
    
        [Fact]
        public void Fact1()
        {
            Console.WriteLine("in fact1. IE is '{0}'", _data.ReferenceToIE);
            // use _data.ReferenceToIE here
        }
    
        [Fact]
        public void Fact2()
        {
            Console.WriteLine("in fact2. IE is '{0}'", _data.ReferenceToIE);
            // use _data.ReferenceToIE here
        }
    
        public void Dispose()
        {
            Console.WriteLine("in Dispose of MyTestClass");
        }
    }
    
    public class WatinFixture : IDisposable
    {
        public string ReferenceToIE = null;
    
        public WatinFixture()
        {
            // start IE here
            Console.WriteLine("Starting IE ...");
            ReferenceToIE = "If you see this string - then browser reference is not empty.";
        }
    
        public void Dispose()
        {
            // close IE here
            Console.WriteLine("Closing IE ...");
            ReferenceToIE = null;
            }
        }
    

    Output:

    Starting IE ...
    in constructor of MyTestClass
    setting data for test
    in fact1. IE is 'If you see this string - then browser reference is not empty.'
    in Dispose of MyTestClass
    in constructor of MyTestClass
    setting data for test
    in fact2. IE is 'If you see this string - then browser reference is not empty.'
    in Dispose of MyTestClass
    Closing IE ...