简体   繁体   English

使用 googlemock 模拟正在测试的函数的内部调用

[英]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:我是 Google Mock 的新手,根据我对文档和在线资源的理解,我无法确定我的问题的解决方案:

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().现在我正在尝试为 A::fun1() 编写一个 Google 测试。 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?有人可以帮助我了解这是否可以用当前形式的 Google Mock 进行模拟? 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.更新:只要class BA::fun1()内实例化,无论如何都很难模拟B 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.对您来说可能是一个可行的解决方案,可以欺骗构建环境进行测试,并为提供模拟的class B提供声明和定义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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