How can I check contracts with NUnit?

I have an abstract class with abstract methods, and its subclasses that override this method must maintain a certain contract. (I do not mean contracts for .NET code, but the very concept of code contracts in itself). The test code for this contract may be the same. How can I test this contract with NUnit across all subclasses while still maintaining the DRY principle (without repeating myself)?

(I am stuck with NUnit due to reasons out of my control and not relevant to this question).

+3


source to share


1 answer


you can create a base test class with an abstract method to get an implementation for testing, and then create a derived instance for each derived class for testing.

Something like that



[TestClass]
public abstract class TestBase
{
     protected abstract IMyInterface GetObjectToTest();

     [Test]
     public void TestMethod()
     {
          IMyInterface objectToTest = GetObjectToTest();
          //Do your generic test of all implementations of IMyInterface
          objectToTest.Setup();
          //...
          Assert.Equal(objectToTest.Property,100);
          //etc
     }
}

[TestClass]
public class ConcreteTestClass : TestBase
{
    protected override GetObjectToTest()
    {
         return new ConcreteImplementationOfIMyObject();
    }

    [Test]
    public void TestConcreteImplementationOfIMyObjectSpecificMethod()
    {   
        //test method for stuff which only applies to ConcreteImplementationOfIMyObject types
    }
 }

      

Using this method, you put all your tests that apply to all instances of the interface in the base class, and then you put any tests that are implementation-specific in that test class.

+3


source







All Articles