What is the difference between gtest and gmock?

前端 未结 4 1270
孤城傲影
孤城傲影 2021-02-03 19:46

I\'m trying to understand the purpose of google-mock, Google\'s C++ mocking framework.

I have already worked with gtest earlier, but still I ca

4条回答
  •  鱼传尺愫
    2021-02-03 20:17

    Suppose you're writing a piece of code that needs to interact with an unpredictable, expensive, external system (e.g. a Web site, a large database, a physical sensor, etc.) Your code needs to keep working when the external system times out, or gives you error messages, or gives you inconsistent data. How can you test whether your code actually meets those requirements?

    Well, you could run it against an actual Web site/database/sensor/whatever, a whole bunch of times, and hope you luck into all the error conditions that your code is supposed to handle. Obviously a fairly expensive and unreliable testing strategy.

    So instead, you write something that satisfies the same interface as the Web site/database/sensor/whatever, but which you've programmed to produce certain "canned" responses (errors, timeouts, inconsistent data, etc.) Your tests will now run much faster (because they don't face the overhead of a real Web site/database/sensor/whatever), and they're predictable. Unfortunately, it takes a lot of coding to write up a separate "mock" Web site/database/sensor/whatever for each scenario you need to test. The more work it is, the less likely you are to do it. Result: inadequately tested code.

    Gmock and its relatives automate a lot of this stuff, so you can specify the desired "canned" behavior in the middle of the test itself, at the cost of only a few lines of code. If tests are easy to write, you're likely to write more of them, and therefore more likely to discover bugs before shipping the code :-)

    BTW, this implies that you also need "dependency injection": your code needs to take in a parameter of the interface type, and you need to be able to pass in either a mock object (for unit-testing) or the "real" Web site/database/sensor/whatever (for real-world use).

提交回复
热议问题