[英]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 - 我建议您做的是两者之一-
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.