简体   繁体   English

在C ++中模拟非类方法

[英]Mocking non-class methods in c++

I am trying to refactor code in a legacy application and ran into a situation where the code looks something like this 我正在尝试在旧版应用程序中重构代码,并遇到代码看起来像这样的情况

namespace DB
{
    void GetDataBase(IDataBase** db);
}

There are a lot of different places that this gets called from, and I want to test those methods but replace the result returned. 有很多不同的地方可以调用此方法,我想测试这些方法,但要替换返回的结果。 Is there a certain design I can use to get this mocked correctly? 我可以使用某种设计来正确模拟吗?

what I have is this but it doesn't seem like a good way to go, though it works 我所拥有的就是这个,但是它虽然可行,但似乎并不是一个好方法

namespace DB
{
    void GetDataBase(IDataBase** db);
    void SetTestDataBase(IDataBase* db);
}

There are a lot of other similar situations and I would love to get some thoughts on how this can be improved. 还有许多其他类似的情况,我很乐意就如何改善这种情况提出一些想法。

The way you suggested is OK, but it pollutes the testing code and you will probably need more then one method like this. 您建议的方式是可以的,但是它会污染测试代码,因此您可能需要的不止一种这样的方法。 Also note that it might not work if there are static variables that are initiated and use this function. 另请注意,如果有静态变量被初始化并使用此函数,则此方法可能不起作用。

What i suggest doing is either one of the two - 我建议您做的是两者之一-

  1. Clean the code, this is not a complicated function with lots of dependencies, you can easily change it into a simple factory call. 清理代码,这不是一个具有很多依赖关系的复杂函数,您可以轻松地将其更改为简单的工厂调用。 To avoid going over all the functions that use it, you can create a macro that does it for you. 为了避免遍历使用它的所有功能,您可以创建一个为您执行的宏。 The factory can then use an #ifndef statement to determine weather to take your mock or the real code. 然后,工厂可以使用#ifndef语句来确定天气,以使用模拟或真实代码。 (compile the testing code with the define statement and the production code without it) (使用define语句编译测试代码,不使用define语句编译生产代码)
  2. You can replace the implementation at linkage time. 您可以在链接时替换实现。 When compiling the production code, link it with the real implementation; 编译生产代码时,将其与实际实现链接; but when you compile the test, link it with your mock to return an object of your liking. 但是当您编译测试时,请将其与您的模拟链接起来以返回您喜欢的对象。

Both ways make sure that no static methods that are called before the main are using the get method you want to mock. 两种方法都确保没有在main之前调用的静态方法正在使用您要模拟的get方法。

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

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