简体   繁体   English

使用 googlemock 由聚合对象调用的模拟函数

[英]Mock function called by aggregate object using googlemock

I have s scenario where in a local object is instantiated to call a method of that class ie setSessionId() .我有一个场景,其中在本地对象中实例化以调用该类的方法,即setSessionId() Defination of setSessionId is as follows: setSessionId 的定义如下:

int Cli::setSessionId()
{
    SessionHandler oHandleSession;
    return oHandleSession.getSessionId(sSessionId);
}

now in order to mock functions of SessionHandler I have used macros to add virtual keyword before the functions I want to mock, in this case getSessionId() as this class is not abstract and functions are not pure virtual.(I know about Hi-Perf Dependency Injection but dont want to go in it at this stage)现在为了模拟SessionHandler函数,我使用宏在要模拟的函数之前添加virtual关键字,在这种情况下getSessionId()因为这个类不是抽象的,函数也不是纯虚拟的。(我知道 Hi-Perf依赖注入但现阶段不想进入)

Had the case been this如果是这样的话

int Cli::setSessionId(SessionHandler* oHandleSession)
{
  ...
  return oHandleSession->getSessionId(sSessionId);
}

It would have been simple to just pass the mocked object to the function setSessionid() but since aggregation is used, how can I mock this function getSessionId() ?将模拟对象传递给函数setSessionid()本来很简单,但是由于使用了聚合,我如何模拟这个函数getSessionId()

You can use static polymorphism or you can use link-time substitution.您可以使用静态多态,也可以使用链接时替换。

For static polymorphism you do something like this:对于静态多态性,您可以执行以下操作:

class DefaultSessionHandler {
  // methods implemented as you do now
};

template <typename T>
class SessionHandlerT {
  // methods implemented in terms of delegation to methods on T
};

using SessionHandler = SessionHandlerT<DefaultSessionHandler>; 

This can be a little cumbersome and can introduce additional compile times and while it can be made to work, I'm not much of a fan of this approach, even though I've done it multiple times before.这可能有点麻烦,并且会引入额外的编译时间,虽然它可以工作,但我不太喜欢这种方法,即使我以前做过多次。

With link-time substitution, you provide an alternate implementation of SessionHandler and resolve the situation at link time.通过链接时替换,您可以提供SessionHandler的替代实现并在链接时解决这种情况。 This means you have some other implementation of the SessionHandler class that does something different even though it has the same name.这意味着您有一些SessionHandler类的其他实现,即使它具有相同的名称,它也会做一些不同的事情。 Again, this is cumbersome but can be made to work.同样,这很麻烦,但可以使其起作用。

Both of these methods have their own sets of problems and pain that they introduce.这两种方法都有各自的问题和痛苦。 A better method of unit testing is to simply use dependency injection by refactoring the SUT.一种更好的单元测试方法是通过重构 SUT 来简单地使用依赖注入。

Another approach is to forego unit testing and only perform integration testing.另一种方法是放弃单元测试而只执行集成测试。 This also has it's own set of problems.这也有它自己的一系列问题。

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

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