c++unit-testingstatic-methodscxxtest

Testing a class that depends on static functions of another class


I am currently working on a class that uses another class which has only static functions.

Everything worked fine until I tried testing my class.

Here is a simple code example of the problem:

class A {
    static String getSometing() {
        return String("Something: ") + heavyCalculation().asString();
    }
}

class B {
    B() {}
    ~B() {}
    String runSomething(const String& name) {
        if(name.equals("something")) {
            return A::getSomething();
        } else {
            return "Invalid name!";
        }
    }
}

Assuming class A is working correctly (and has been tested by its unit tests), I would like to check the runSomething function in class B.

My first option would be creating mocks for the inner classes (In this sample - class A), but in that case it will give me nothing to inherit from A because it has only static functions.

My second option is to encapsulate the calls for A class in private functions inside B so I could control their return values (although choosing this option will make the good a little bit more complex).

My question to you is: Are there in better ways to test C++ classes that depends on static classes/functions than my current options?

Thanks in advance,

Tal.


Solution

  • I have had success in unit testing in similar situations by refactoring out the references to the static functions (in my case it was external dependencies) into new private functions and overwriting them on the tested stub, so I can recommend this approach

    If the refactored functions remain private, they should not impact greatly on the complexity of the design and they should be small enough not to negatively impact on the readability of the code.