jeudi 27 juin 2019

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

So I have something like so:

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());
}

It is clear that calculateThingUnitTest is a proper unit test because it initializes a class, gives it some literal-defined independent value in the constructor, and the assertion it makes is based only on calculateThing(), so it tests one "unit" of the application.

However, calculateOtherThingUnitTest calls calculateOtherThing which then makes a call to calculateThing to determine if the result is correct. So, if calculateThing ends up failing, calculateOtherThing will fail as well.

In order to prevent this, you would want to put some mock value in place of calculateThing, and you could achieve this by inserting a new member variable into MyClass and making calculateThing load into that member variable. Then before calling calculateOtherThing you could just insert a literal value into this member variable and you would have a proper unit test.

Adding a new member variable and exposing it to the public seems extraordinarily excessive, however. Is there a better way to achieve this?

Aucun commentaire:

Enregistrer un commentaire