繁体   English   中英

如果一个功能依赖于另一个功能,您如何将该内部功能放在模拟数据中以进行单元测试?

[英]If a function depends on another function, how do you emplace that inner-function with mock data for unit testing?

所以我有这样的事情:

class MyClass {
    private myVar;

    public MyClass(someValue) {
        // Performs some operation to determine myVar
    }

    public double calculateThing() {
        // Returns some arithmetic operation on myVar
    }

    public double calculateOtherThing() {
        newVar = calculateThing();
        // Returns some arithmetic operation on newVar
    }
}

calculateThingUnitTest() {
    MyClass class = new MyClass(someValue);

    Assert::AreEqual(someConstant, class.CalculateThing());
}

calculateOtherThingUnitTest() {
    MyClass class = new MyClass(someValue);

    Assert::AreEqual(someOtherConstant, class.CalculateOtherThing());
}

显然, calculateThingUnitTest是一个适当的单元测试,因为它初始化了一个类,并在构造函数中为其提供了一些按字面值定义的独立值,并且其做出的断言基于calculateThing() ,因此它测试了一个“单元”应用。

但是, calculateOtherThingUnitTest调用calculateOtherThing ,然后再调用calculateThing来确定结果是否正确。 因此,如果calculateThing最终失败,那么calculateOtherThing也将失败。

为了防止这种情况,您可能希望将一些模拟值替换为calculateThing ,并且可以通过在MyClass插入一个新的成员变量并向该成员变量中加载calculateThing来实现此目的。 然后,在调用calculateOtherThing之前,您只需在该成员变量中插入一个文字值即可进行适当的单元测试。

但是,添加一个新的成员变量并将其向公众公开似乎太过分了。 有没有更好的方法来实现这一目标?

注意:尽管我使用的是伪代码,但是我正在C#中使用Visual Studio .Net单元测试项目。

您正在寻找的是部分模拟。 您需要模拟未测试的方法。 而且您需要保留默认方法下的测试方法。 因此,当您调用被测方法时,不会模拟所有其他方法。

因此,您可以模拟calculateThing,然后直接测试其他方法。

Stackoverflow链接

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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