0
votes

I'm looking at GMock and trying to decide if it is going to be feasible for some unit testing I want to do.

If I understand correctly, any class you Mock has to have an interface that the mock can be created from, and any class you want to test, has to be able to accept the mock via injection.

Am I correct so far?

If I am correct, so far, I do not see how it is going to help me in testing classes that use a class from a third party.

For example:

Suppose I wrote a ChatClient class, and when implementing it I use QWebSocket from the Qt Library. ChatClient has a member ChatClient::m_socket of type QWebSocket.

Now, there is no interface for GMock to create a mock websocket from, and my chat client doesn't take an interface via dependency injection in production code. How a the QWebSocket works is so specific, that I'd never be able to use a different concrete implementation.

However, I do want to test that my ChatClient, calls connect when its supposed to, passes the correct bytes to its calls to QWebSocket::sendBinaryMessage, reacts to incoming message correctly, etc., and it seems a mock framework would be useful to test my ChatClient in that way so I don't have to actually connect to a network.

What do I do, or is this just not doable in C++ like it is in other languages because we don't have reflection?

Do I just create my own interface for the third party class, with every call I make to it, forward it to the third party class, and then have my ChatClient take that interface, even though I will never ever use another concrete implementation, just to enable testing?

1
For what it's worth, I had a lot of the same frustrations, which is why I made Mimicc. It might help you here too. You would "compile" the library headers you want to mock using the mimicc command, and it will create object files with mock implementations that you can link in to your test executable. I included an example in the user guide for using with GoogleTest. Take a look, I really think it could make your life easier.Jon Reeves
@JonReeves Does it work with Qt signals and slots?Christopher Pisz
@ChistopherPisz mimicc itself doesn't parse the Qt preprocessor tags (like signals/slots), it acts a second front-end for the clang compiler driver. That said, you should be able to use the Qt moc tool to convert Qt decorated code into ordinary cpp code and run mimicc on that. I don't personally have a ton of experience with Qt, but let me see if I can try it out myself and give you an example to follow. Shoot me an email at [email protected] if you want to follow up on it.Jon Reeves

1 Answers

0
votes

"Just to enable testing" is would be good enough for me, but I agree that if there're many methods there would be a lot of boilerplate...

See static dependency injection: Mock static method from external Class (that I can't change!)