Saturday, March 20, 2010

Testing multiple implementations

Challenge: Run automated tests of multiple implementations of an interface, for example one repository for Sql Server and another for MySql.

A solution: Have one test class for one of the implementations, and create a derived test class for the other implementation, which injects the proper implementation in the constructor of the first test class.

Example with NUnit:

[TestFixture]
public class CustomerRepositoryTests
{
   private ICustomerRepository _repository;

   public CustomerRepositoryTests() :
      this(new CustomerRepository())
   {
   }

   public CustomerRepositoryTests(ICustomerRepository repository)
   {
      _repository = repository;
   }

   [Test]
   public void Add_ValidCustomer_Ok()
   {
      // Arrange:
      var customer = new Customer();

      // Act:
      _repository.Add(customer);
   }

}

[TestFixture]
public class MySqlCustomerRepositoryTests :
   CustomerRepositoryTests
{
   public MySqlCustomerRepositoryTests() :
      base(new MySqlCustomerRepository())
   {
   }
}

No comments: