【问题标题】:Is there a practical way to reuse a set of test methods against different stubs in the Microsoft Unit Test Framework?是否有一种实用的方法可以针对 Microsoft 单元测试框架中的不同存根重用一组测试方法?
【发布时间】:2015-01-29 16:06:13
【问题描述】:

我正在使用 Visual Studio 2012 下的 Microsoft 单元测试框架来测试一个 C# 类,该类表示对某种数据库的数据访问层。

为了能够对其进行单元测试,我创建了一个类使用的存根,而不是所述数据库。 我的测试类具有以下结构:

[TestClass]
public class UnitTests {

    MyStub stub;

    [TestInitialize]
    public void InitializeContext() { // Construct stub  }

    [TestCleanup]
    public void CleanupContext() { // Dispose stub }

    [TestMethod]
    public void Test1() { ... }

    [TestMethod]
    public void Test2() { ... }

    ...
}

效果很好。

我现在想编写第二个测试类,对不同的存根执行相同的测试,因此我想重用代码,但我无法通过继承来实现这一点(继承 UnitTests 并覆盖InitializeContext()CleanupContext()),因为 TestMethod 属性似乎不可继承。

有没有一种实用的方法来实现这一点?如果有,是哪一个?

【问题讨论】:

  • 您是否将TestClass 属性添加到派生类的顶部?

标签: c# unit-testing visual-studio-2012


【解决方案1】:

在我看来,您有一组属于您想要在不同环境中运行的“测试集”的测试。

我个人通过在实际测试之外实现测试来解决这个问题,并使用参数调用外部实现的测试:

[TestClass]
public class UnitTests1 {

    MyStub stub;

    [TestInitialize]
    public void InitializeContext() { // Construct stub  }

    [TestCleanup]
    public void CleanupContext() { // Dispose stub }

    [TestMethod]
    public void Test1() { StubTests.TestMyStub(stub); }

    [TestMethod]
    public void Test2() { StubTests.TestMyStub2(stub); }

    ...
}


[TestClass]
public class UnitTests2 {

    MyStub stub;

    [TestInitialize]
    public void InitializeContext() { // Construct stub  }

    [TestCleanup]
    public void CleanupContext() { // Dispose stub }

    [TestMethod]
    public void Test1() { StubTests.TestMyStub(stub); }

    [TestMethod]
    public void Test2() { StubTests.TestMyStub2(stub); }

    ...
}

“StubTests”类不使用任何注释,而是使用函数中的参数引用外部依赖项(例如移交存根)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-30
    • 2016-01-19
    • 1970-01-01
    相关资源
    最近更新 更多