Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you unit test an interface?

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)

like image 798
Chetan Avatar asked Jun 25 '10 22:06

Chetan


People also ask

How do you test an interface in unit testing?

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.

Do we need to test interface?

Introduction. For a computer, an interface can be APIs, web services, etc. The communication between the different components of a software or an application or a website can affect the overall performance hence this communication i.e. the interface also needs to be tested and verified.

Can we test interface?

You can't. It has no implementation. You do want to test each and every class that implements this interface. To check that any class that implements the interface meets the expectations of the clients of that interface.


1 Answers

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();     } } 
like image 61
Tim Lloyd Avatar answered Sep 22 '22 15:09

Tim Lloyd