views:

117

answers:

4

For example, there is a interface IMyInterface, and three classes support this interface:

class A : IMyInterface
{
}

class B : IMyInterface
{
}

class C : IMyInterface
{
}

In the simplest way, I could write three test class : ATest, BTest, CTest and test them separately. However, since they support the same interface, most test code would be the same, it's hard to maintain. How can I use a simple and easy way to test a interface that is supported by different class?

(previously asked on the MSDN forums)

+1  A: 

Could create methods that take a parameter of type IMyInterface and have the actual test methods just call those methods passing in different concrete classes.

Davy8
A: 

You do not test the interface directly, but you may write an abstract class that tests the contract a particular implementation should extend. A test of a concrete class would then extend the abstract class

Kathy Van Stone
+7  A: 

To test an interface with common tests regardless of implementation, you can use an abstract test case, and then create concrete instances of the test case for each implementation of the interface.

The abstract (base) test case performs the implementation-neutral tests (i.e. verify the interface contract) while the concrete tests take care of instantiating the object to test, and perform any implementation-specific tests.

mdma
+5  A: 

If you want to run the same tests against different implementers of your interface using NUnit as an example:

public interface IMyInterface {}
class A : IMyInterface { }
class B : IMyInterface { }
class C : IMyInterface { }

public abstract class BaseTest
{
    protected abstract IMyInterface CreateInstance();

    [Test]
    public void Test1()
    {
        IMyInterface instance = CreateInstance();
        //Do some testing on the instance...
    }

    //And some more tests.
}

[TestFixture]
public class ClassATests : BaseTest
{
    protected override IMyInterface CreateInstance()
    {
        return new A();
    }

    [Test]
    public void TestCaseJustForA()
    {
        IMyInterface instance = CreateInstance();   
        //Do some testing on the instance...
    }

}

[TestFixture]
public class ClassBTests : BaseTest
{
    protected override IMyInterface CreateInstance()
    {
        return new B();
    }
}

[TestFixture]
public class ClassCTests : BaseTest
{
    protected override IMyInterface CreateInstance()
    {
        return new C();
    }
}
chibacity
This is a good example of the correct answer.
Chetan