I started using xUnit.Net a few weeks ago. My first question was how to do the things I was used to do in other testing frameworks like MSTest or NUnit, especially when using this framework for unit testing and for higher level tests like Selenium RC web tests. Here’s how I went about it.

I am going to show some scenarios I have run to convert MSTest to xUnit.Net having the following class,

Running the Tests (CLASSINITIALIZE – CLASSCLEANUP)

RUNNING THE TESTS (CLASSINITIALIZE – CLASSCLEANUP)
using Microsoft.VisualStudio.TestTools.UnitTesting;

[TestClass]
public class AdminPageTest
{
    static SeleniumWebTestContext test = new SeleniumWebTestContext();

    [ClassInitialize()]
    public static void ClassInitialize() 
    {
        new LoginPage(test).LoginUser(“maria”, “******”);
    }

    [ClassCleanup()]
    public static void ClassCleanup() 
    {
        new AdminPage(test.Driver).Logout();
        test.StopWebTestContext();
    }

    [TestCategory("WebTest"), TestMethod]
    public void TestViewMyProfile()
    {
        var profileWindow = new AdminPage(test.Driver).SelectMyProfile();
        Assert.IsTrue(profileWindow.CheckFirstName(“Maria”));
        profileWindow.Close();
    }

    [TestCategory("WebTest"), TestMethod]
    public void TestAdminSearchUser()
    {
        var userWindow = new AdminPage(test.Driver).SelectUserManagement();
        userWindow.Search("Marcano Maria");
        Assert.IsTrue(adminTab.VerifyEmail("[email protected]"));
    }
}

Note that SeleniumWebTestContext is holding information about Selenium RC and starts the server.

ClassInitialize – ClassCleanup / IUseFixture

Sometimes we require sharing information among the methods defined in a class. For example, in web tests, we want to share the logged in user’s information, execute different actions and validations and log out at the end.
Converting MSTest ClassInitialize and ClassCleanup to the equivalent implementation in xUnit.Net will look like the following class:

using Xunit;

public class AdminPageTest : IUseFixture
{
    SeleniumWebTestContext test;

    public AdminPageTest()
    {  
    }

    public void SetFixture(LoggedUserContext usrContext)
    {
        test = usrContext.Test;
    }
    ...
}

IUseFixture is used to pass information shared by the tests, in this case information selenium’s logged user. The LoggedUserContext class will look like this,

public class LoggedUserContext : IDisposable
{    
    public SeleniumWebTestContext Test;    
    public LoggedUserContext()    
    {        
        Test = new SeleniumWebTestContext();        
        new LoginPage(Test).LoginUser(“maria”, “******”);    
    }    

    public void Dispose()    
    {       
        new AdminPage(Test.Driver).Logout();
        Test.StopWebTestContext();
    }
}

In my next post I will show a solution for implementing an equivalent MSTest TestCategory attribute in xUnit.Net.