Testing a class that depends on the static functions of another class

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

Everything worked fine until I tried to test my class.

Here is a simple problem code example:

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 was tested by its unit tests), I would like to test the runSomething function in class B.

My first option would be to create mocks for inner classes (in this example, class A), but in this case it will not let me inherit anything from A, since it has only static functions.

A B, ( ).

: ++, /, ?

,

Tal.

+3
6

, ( ) ,

, , , .

+3

, . , A A.cpp B B.cpp, B B_test.cpp.

A_mock.cpp

class A
{
    static String getSometing() {
        return String("Expected Something");
    }
};

, B_test, A_mock.o, A.o.

g++ -Wall B_test.cpp B.cpp A_mock.cpp
+1

A. , , .

0

? .

A ( ++ ) AInterface. A () AInterface .

B - m_A. MockClassA, AInterface. MockClassA B m_A .

class AInterface
{
   virtual String getSomething() = 0;
}

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

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

class MockClassA : public AInterface
{
    String getSometing() {
        return String("Whatever I want. This is a test");
    }
}   

void test ()
{
   // "MockClassA" would just be "A" in regular code
   auto instanceOfB = B(MockClassA());

   String returnValue = instanceOfB.runSomething("something");
   :
   :
}
0

: ", !"

. A B.

-1

(B<A>), , . , , , . , , Java - , , ++, .

template<typename T> class BImpl {
    String runSomething(const String& name) {
        if(name.equals("something")) {
            return T::getSomething();
        } else {
            return "Invalid name!";
        }
    }
};
typedef BImpl<A> B; // Just plugs in to existing code.

mock A, . Infact, - - CRTP.

class A : public BImpl<A> {
    String getSomething() {
        // Now it non-static! IT A MIRACLE!
    }
}

.

-1

Source: https://habr.com/ru/post/1772569/


All Articles