如何在 MSTest 中正确重用测试代码

How to properly reuse test code in MSTest

我们已经开始引入一些行为测试,试图测试一些软件模块,就像一个完整的黑盒子。 这个测试套件是使用从基础测试 class 的继承编写的,以便于组织。

现在我们想重用这个测试套件来测试另一个接口兼容的模块。 我们能够找到的解决方案是继承测试 class,并实现另一个构造函数。 我想确认没有更好的选择,因为为每个测试套件 class 编写重复继承的 classes 似乎是错误的。

[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;
    ...
}

如果您只想按原样重新使用测试代码,但要使用不同的被测模块,继承似乎是最直接的,因为每个测试都需要一个单独的测试方法,而继承是无需自己输入即可做到这一点的唯一方法。这不应该引入任何重复,因为您只需要重新实现每个 subclass.

中实际不同的部分

如果您的问题在于您在测试用例 class 构造函数中构建测试夹具,另一种方法是应用 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.

话虽这么说,如果您真的想将它们全部保存在同一个测试用例中class,如果您实现创建方法,您也许可以这样做对于您的基础测试用例 class 上被测试的各个模块,然后将这些方法的名称传递给您的测试方法并使用反射调用它们。应该有一个属性允许您将参数传递给测试方法,这在 in this answer 中进行了讨论。但是,这种方法的可行性只是我的推测,您可能 运行 有使您的测试更加模糊的风险。