如果功能取决于另一个函数,则如何使用模拟数据进行单位测试的模拟数据函数



所以我有类似的东西:

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之前,您可以将文字值插入此成员变量,您将进行适当的单元测试。

添加一个新的成员变量并将其暴露给公众似乎非常过分。有更好的方法可以实现这一目标吗?

注意:尽管我正在使用伪代码,但我正在使用Visual Studio .NET单元测试项目在C#工作。

您要寻找的东西是部分模拟。您需要模拟未在测试的方法。而且,您需要像默认实现一样,将测试方法放置。因此,当您调用正在测试的方法时,所有其他方法都没有被嘲笑。

因此,您可以模拟计算,然后只测试其他方法。

stackoverflow链接

最新更新