简体   繁体   中英

How to properly reuse test code in MSTest

We've started to introduce some behavior tests that try to test some of out software modules like a complete black box. This test suite was written using inheritance from base test class for easier organization.

Now we'd like to reuse this test suite for the testing of another interface-compatible module. The solution we were able to find was to inherit the test class, and implement another constructor. I'd like to confirm that there's no better option, because writing duplicate inherited classes for each of the test suite class seems wrong.

[TestClass]
public class RouModel_Basic_RunnerBasic : ROUModelTest_Basic
{
    public RouModel_Basic_RunnerBasic() : base()
    {
        //init basic model here
        model = basicModel;
    }
}
[TestClass]
public class RouModel_Basic_RunnerOther : ROUModelTest_Basic
{
    public RouModel_Basic_RunnerOther() : base()
    {
        //init other model here
        model = otherModel;
    }
}

public class ROUModelTest_Basic : RouModelTest
{
   [TestMethod]
   public void TestABC() 
   {
       string input = "abc"
       var result = model.run(input);
       Assert.AreEqual("123", result);
   }
}

public class RouModelTest 
{
    protected IModelTest model;
    ...
}

If you just want to re-use the test code as-is but with a different module under test, inheritance seems to be the most straightforward, since you will need a separate test method for each test, and inheritance is the only way to do that without having to type them yourself. This shouldn't introduce any duplication, since you only have to re-implement the parts that are actually different in each subclass.

If your issue is with the fact that you are building your test fixture in the test case class constructor, an alternative would be to apply the Template Method design pattern to your test methods, and add a virtual creation method for the module under test that subclasses can override to create instances of the specific module you want them to test. Alternatively, you could create a test setup method and mark it with the appropriate attribute, as described in this answer .

That being said, if you really want to keep them all in the same test case class, you might be able to do so if you implement creation methods for the individual modules under test on your base test case class, and then pass the names of those methods to your test methods and call them using reflection. There should be an attribute that allows you to pass arguments to test methods, which is discussed in this answer . However, the feasibility of this approach is just speculation on my part, and you might run the risk of making your tests more obscure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM