Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

same unit test for different implementations

Tags:

java

mstest

Let's say I have two implementations of a search algorithm that return the same result for the same input. They both implement the same interface.

How can I use a single [TestClass] for testing both implementations, rather then create two test files with eventually the same logic ?

Can I tell MSUnit to launch one of the tests twice with different constructor parameter?
Perhaps I should (n)inject it somehow ?

like image 361
Alex Avatar asked Mar 22 '13 11:03

Alex


People also ask

Should unit tests be in the same package?

Unit tests can be in any package. In essence they are just separate classes used to test the behaviour of the class being tested.

Can unit tests depend on each other?

Tests should never depend on each other. If your tests have to be run in a specific order, then you need to change your tests. Instead, you should make proper use of the Setup and TearDown features of your unit-testing framework to ensure each test is ready to run individually.

What is single unit testing?

Unit testing is a software development process in which the smallest testable parts of an application, called units, are individually and independently scrutinized for proper operation. This testing methodology is done during the development process by the software developers and sometimes QA staff.


1 Answers

Use an abstract test class:

[TestClass]
public abstract class SearchTests
{
    private ISearcher _searcherUnderTest;

    [TestSetup]
    public void Setup()
    {
        _searcherUnderTest = CreateSearcher();
    }

    protected abstract ISearcher CreateSearcher();

    [TestMethod]
    public void Test1(){/*do stuff to _searcherUnderTest*/ }

    // more tests...

    [TestClass]
    public class CoolSearcherTests : SearcherTests
    {
         protected override ISearcher CreateSearcher()
         {
             return new CoolSearcher();
         }
    }

    [TestClass]
    public class LameSearcherTests : SearcherTests
    {
         protected override ISearcher CreateSearcher()
         {
             return new LameSearcher();
         }
    }
}
like image 99
tallseth Avatar answered Sep 30 '22 20:09

tallseth