Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Visual studio unit test for different implementation of interface

I need do unit testing for two implementation classes of one particular interface. The unit test class is generic covered all the necessary test for the interface. I want to instantiate the implementation class in test unit class TestInitialize method.

Is there any way I could force the test class run twice with different implementation class instance.

[TestClass]
public class MyFixture
{
    [TestInitialize()]
    public void MyTestInitialize()
    {
        ITest mockInstance = new TestImplement1();
        //ITest mockInstance = new TestImplement2();
    }

    [TestMethod]
    public void Test1 ()
    {
        mockInstance.Func1();
        ...  
    }

    [TestMethod]
    public void Test2 ()
    {
        ...  
    }

    ...other unit tests

 }
like image 780
Tao Avatar asked Nov 16 '10 22:11

Tao


2 Answers

For this pattern, typically you would have a base test class with the test methods, and then you would subclass it and fill in the setup method. So it would become something like this: (I use NUnit, so I apologize if the test framework methods are a little off)

// don't mark this one as TestClass!
public abstract class MyBaseFixture
{
    protected ITest mockInstance;

    [TestMethod]
    public void Test1 ()
    {
        Assert(this.mockInstance.Func1() == 0);
    }
}

[TestClass]
public class MyConcreteFixture : MyBaseFixture
{
    [TestInitialize]
    public void Setup()
    {
        this.mockInstance = new ConcreteInstance1();
    }
}    

[TestClass]
public class MyOtherConcreteFixture : MyBaseFixture
{
    [TestInitialize]
    public void Setup()
    {
        this.mockInstance = new ConcreteInstance2();
    }
}
like image 69
Mark Rushakoff Avatar answered Nov 16 '22 01:11

Mark Rushakoff


You should check out Greg Young's interface invariant NUnit plugin: https://github.com/gregoryyoung/grensesnitt

like image 32
Jon Wingfield Avatar answered Nov 16 '22 03:11

Jon Wingfield