<p>If I have interface IFoo, and have several classes that implement it, what is the best/most elegant/cleverest way to test all those classes against the interface?</p>

<p>I'd like to reduce test code duplication, but still 'stay true' to the principles of Unit testing.</p>

<p>What would you consider best practice? I'm using NUnit, but I suppose examples from any Unit testing framework would be valid</p>

[{'answer_id': 39008, 'author': 'graham.reeds', 'author_id': 342, 'author_profile': 'https://Stackoverflow.com/users/342', 'pm_score': 0, 'selected': False, 'text': "<p>I don't use NUnit but I have tested C++ interfaces. I would first test a TestFoo class which is a basic implementation of it to make sure the generic stuff works. Then you just need to test the stuff that is unique to each interface.</p>\n"}, {'answer_id': 39034, 'author': 'Spoike', 'author_id': 3713, 'author_profile': 'https://Stackoverflow.com/users/3713', 'pm_score': 5, 'selected': True, 'text': '<p>If you have classes implement any one interface then they all need to implement the methods in that interface. In order to test these classes you need to create a unit test class for each of the classes.</p>\n\n<p>Lets go with a smarter route instead; if your goal is to <strong>avoid code and test code duplication</strong> you might want to create an abstract class instead that handles the <strong>recurring</strong> code. </p>\n\n<p>E.g. you have the following interface:</p>\n\n<pre><code>public interface IFoo {\n\n    public void CommonCode();\n\n    public void SpecificCode();\n\n}\n</code></pre>\n\n<p>You might want to create an abstract class:</p>\n\n<pre><code>public abstract class AbstractFoo : IFoo {\n\n    public void CommonCode() {\n          SpecificCode();\n    }\n\n    public abstract void SpecificCode();\n\n}\n</code></pre>\n\n<p>Testing that is easy; implement the abstract class in the test class either as an inner class:</p>\n\n<pre><code>[TestFixture]\npublic void TestClass {\n\n    private class TestFoo : AbstractFoo {\n        boolean hasCalledSpecificCode = false;\n        public void SpecificCode() {\n            hasCalledSpecificCode = true;\n        }\n    }\n\n    [Test]\n    public void testCommonCallsSpecificCode() {\n        TestFoo fooFighter = new TestFoo();\n        fooFighter.CommonCode();\n        Assert.That(fooFighter.hasCalledSpecificCode, Is.True());\n    }\n}\n</code></pre>\n\n<p>...or let the test class extend the abstract class itself if that fits your fancy.</p>\n\n<pre><code>[TestFixture]\npublic void TestClass : AbstractFoo {\n\n    boolean hasCalledSpecificCode;\n    public void specificCode() {\n        hasCalledSpecificCode = true;\n    }\n\n    [Test]\n    public void testCommonCallsSpecificCode() {\n        AbstractFoo fooFighter = this;\n        hasCalledSpecificCode = false;\n        fooFighter.CommonCode();\n        Assert.That(fooFighter.hasCalledSpecificCode, Is.True());\n    }        \n\n}\n</code></pre>\n\n<p>Having an abstract class take care of common code that an interface implies gives a much cleaner code design. </p>\n\n<p>I hope this makes sense to you.</p>\n\n<hr>\n\n<p>As a side note, this is a common design pattern called the <strong><a href="http://en.wikipedia.org/wiki/Template_method_pattern" rel="nofollow noreferrer">Template Method pattern</a></strong>. In the above example, the template method is the <code>CommonCode</code> method and <code>SpecificCode</code> is called a stub or a hook. The idea is that anyone can extend behavior without the need to know the behind the scenes stuff.</p>\n\n<p>A lot of frameworks rely on this behavioral pattern, e.g. <a href="http://msdn.microsoft.com/en-us/library/ms178472.aspx" rel="nofollow noreferrer">ASP.NET</a> where you have to implement the hooks in a page or a user controls such as the generated <code>Page_Load</code> method which is called by the <code>Load</code> event, the template method calls the hooks behind the scenes. There are a lot more examples of this. Basically anything that you have to implement that is using the words "load", "init", or "render" is called by a template method.</p>\n'}, {'answer_id': 39036, 'author': 'Jon Limjap', 'author_id': 372, 'author_profile': 'https://Stackoverflow.com/users/372', 'pm_score': 2, 'selected': False, 'text': "<p>I don't think this is best practice. </p>\n\n<p>The simple truth is that an interface is nothing more than a contract that a method is implemented. It is <em>not</em> a contract on either a.) how the method should be implemented and b.) what that method should be doing exactly (it only guarantees the return type), the two reasons that I glean would be your motive in wanting this kind of test.</p>\n\n<p>If you really want to be in control of your method implementation, you have the option of:</p>\n\n<ul>\n<li>Implementing it as a method in an abstract class, and inherit from that. You will still need to inherit it into a concrete class, but you are sure that unless it is explicitly overriden that method will do that correct thing.</li>\n<li>In .NET 3.5/C# 3.0, implementing the method as an extension method referencing to the Interface</li>\n</ul>\n\n<p>Example:</p>\n\n<pre><code>public static ReturnType MethodName (this IMyinterface myImplementation, SomeObject someParameter)\n{\n    //method body goes here\n}\n</code></pre>\n\n<p>Any implementation properly referencing to that extension method will emit precisely that extension method so you only need to test it once.</p>\n"}, {'answer_id': 39363, 'author': 'James A. Rosen', 'author_id': 1190, 'author_profile': 'https://Stackoverflow.com/users/1190', 'pm_score': 4, 'selected': False, 'text': '<p>I disagree with <a href="https://stackoverflow.com/questions/39003/nunit-how-to-test-all-classes-that-implement-a-particular-interface#39036">Jon Limjap</a> when he says,</p>\n\n<blockquote>\n  <p>It is not a contract on either a.) how the method should be implemented and b.) what that method should be doing exactly (it only guarantees the return type), the two reasons that I glean would be your motive in wanting this kind of test.</p>\n</blockquote>\n\n<p>There could be many parts of the contract not specified in the return type.  A language-agnostic example:</p>\n\n<pre><code>public interface List {\n\n  // adds o and returns the list\n  public List add(Object o);\n\n  // removed the first occurrence of o and returns the list\n  public List remove(Object o);\n\n}\n</code></pre>\n\n<p>Your unit tests on LinkedList, ArrayList, CircularlyLinkedList, and all the others should test not only that the lists themselves are returned, but also that they have been properly modified.</p>\n\n<p>There was an <a href="https://stackoverflow.com/questions/26455/does-design-by-contract-work-for-you#34811">earlier question</a> on design-by-contract, which can help point you in the right direction on one way of DRYing up these tests.</p>\n\n<p>If you don\'t want the overhead of contracts, I recommend test rigs, along the lines of what <a href="https://stackoverflow.com/questions/39003/nunit-how-to-test-all-classes-that-implement-a-particular-interface#39034">Spoike</a> recommended:</p>\n\n<pre><code>abstract class BaseListTest {\n\n  abstract public List newListInstance();\n\n  public void testAddToList() {\n    // do some adding tests\n  }\n\n  public void testRemoveFromList() {\n    // do some removing tests\n  }\n\n}\n\nclass ArrayListTest &lt; BaseListTest {\n  List newListInstance() { new ArrayList(); }\n\n  public void arrayListSpecificTest1() {\n    // test something about ArrayLists beyond the List requirements\n  }\n}\n</code></pre>\n'}, {'answer_id': 40959, 'author': 'Emperor XLII', 'author_id': 2495, 'author_profile': 'https://Stackoverflow.com/users/2495', 'pm_score': 1, 'selected': False, 'text': '<p>When testing an interface or base class contract, I prefer to let the test framework automatically take care of finding all of the implementers. This lets you concentrate on the interface under test and be reasonably sure that all implementations will be tested, without having to do a lot of manual implementation.</p>\n\n<ul>\n<li>For <a href="http://www.codeplex.com/xunit" rel="nofollow noreferrer">xUnit.net</a>, I created a <a href="http://www.codeplex.com/TypeResolver" rel="nofollow noreferrer">Type Resolver</a> library to search for all implementations of a particular type (the xUnit.net extensions are just a thin wrapper over the Type Resolver functionality, so it can be adapted for use in other frameworks).</li>\n<li>In <a href="http://www.mbunit.com/" rel="nofollow noreferrer">MbUnit</a>, you can use a <a href="http://weblogs.asp.net/astopford/archive/2008/08/29/mbunit-combinatorial-test.aspx" rel="nofollow noreferrer"><code>CombinatorialTest</code></a> with <code>UsingImplementations</code> attributes on the parameters.</li>\n<li>For other frameworks, the base class pattern <a href="https://stackoverflow.com/questions/39003/nunit-how-to-test-all-classes-that-implement-a-particular-interface#39034">Spoike</a> mentioned can be useful.</li>\n</ul>\n\n<p>Beyond testing the basics of the interface, you should also test that each individual implementation follows its particular requirements.</p>\n'}, {'answer_id': 61561, 'author': 'Andrei Rînea', 'author_id': 1796, 'author_profile': 'https://Stackoverflow.com/users/1796', 'pm_score': 1, 'selected': False, 'text': '<p>How about a hierarchy of [TestFixture]s classes? Put the common test code in the base test class and inherit it into child test classes..</p>\n'}]
['https://Stackoverflow.com/questions/39003', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3024/']