Life is unfair. You work every bit as hard as Joe the Java programmer next to you. Yet as a C++ programmer, you don't get to play with all the fancy programming tools Joe takes for granted.
In particular, without a good mocking framework, mock objects in C++ have to be rolled by hand. Boy, is that tedious! (Not to mention how error-prone it is.) Why should you endure this?
Dread no more. Google Mock is finally here to help! It's a Google-originated open-source framework for creating and using C++ mocks. Inspired by jMock and EasyMock, Google Mock is easy to use, yet flexible and extensible. All you need to get started is the ability to count from 0 to 10 and use an editor.
Think you can do it? Let's try this simple example: you have a ShoppingCart class that gets the tax rate from a server, and you want to test that it remembers to disconnect from the server even when the server has generated an error. It's easy to write the test using a mock tax server, which implements this interface:
class TaxServer {
// Returns the tax rate of a location
// (by postal code) or -1 on error.
virtual double FetchTaxRate(
const string& postal_code) = 0;
virtual void CloseConnection() = 0;
};
ShoppingCart:
class MockTaxServer : public TaxServer { // #1
MOCK_METHOD1(FetchTaxRate, double(const string&));
MOCK_METHOD0(CloseConnection, void());
};
TEST(ShoppingCartTest,
StillCallsCloseIfServerErrorOccurs) {
MockTaxServer mock_taxserver; // #2
EXPECT_CALL(mock_taxserver, FetchTaxRate(_))
.WillOnce(Return(-1)); // #3
EXPECT_CALL(mock_taxserver, CloseConnection());
ShoppingCart cart(&mock_taxserver); // #4
cart.CalculateTax(); // Calls FetchTaxRate()
// and CloseConnection().
} // #5
Remember to download this episode and post it in your office!
Toilet-Friendly Version
No comments:
Post a Comment