简体   繁体   中英

Mocking internal calls of a function being tested using googlemock

I am new to Google Mock and based on my understanding of the documentation and online resources, I could not identify a solution to my problem:

I have the following classes:

class A
{
    public:
        A() { }
        int fun1()
        {
            //Some code
            B b;
            x = b.fun2();
            //Some other code
        }
};
class B
{
    public:
        B() { }
        int fun2()
        {
            //Some code
            y = C::fun3();
            //Some code
        }
};
class C
{
    public:
        static int fun3()
        {
            //Read a file and provide success if a certain pattern is found
        }
};

Now I am trying to write a Google test for A::fun1(). But because of the structure of the code (all the calls are through objects and I do not have a base class using which I can initialize a mock etc., I am not able to mock this successfully.

Can someone help me understand if this is mockable with Google Mock in its current form? Please note that I am not allowed to change the original source code.

You can only do this as long the class under test can be configured using static interfaces (ie template parameters). See here for more information: Mocking Nonvirtual Methods .

Another alternative may be to introduce wrapper interfaces in your class under test, that can be mocked as usual: Alternative to Mocking Concrete Classes .

If you can't change any of the code it's not possible IMHO.

UPDATE : As long class B is instantiated inside A::fun1() , it will be hard to mock B anyway. It should be passed as parameter, thus you have a chance to control the instantiation in your test method.

May be a viable solution for you could be to spoof the build environment for testing, and provide a declaration and definition for class B that provides a mock.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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