Faking the Turtle Class
|Top Previous Next|
We'd like to create a fake instance of the Turtle class. By default, faking an instance of a class, will cause all of that instance's methods to behave like empty methods. If those methods are non-void, they will return either default values for simple values like integers and doubles, and for functions that return other classes, a faked instance will return yet another fake object.
By faking a class, we basically override all of its methods at runtime, so that by default, none of them really do anything.
To fake a new instance, we simply use the FAKE macro provided in Isolator.h:
what we'll get in the printout is '0' because by default GetX() returns the default value, and has no implementation.
Note: We don't need to define our own class that inherits from the Turtle class, and how we don't need to define each method's default fake behavior. All of this is done for us freely, at runtime, by using just one line of code.
How to use it
Since creating fake objects is so easy with Isolator++, you can just create them directly in a unit test.
Here's an example using GoogleTest:
Tearing Down and Cleaning Up
Note in the previous test that at the end of each test, we override the TearDown virtual method of the test framework. we are calling ISOLATOR_CLEANUP - this is very important, since we need to "clean up" the expectations between tests, such as the behavior of static methods, global functions and future objects.
Controlling Fake Behavior
Now we can tell our fake object to return some number:
Here we're using the special WHEN_CALLED macro, which is part of Isolator++.
When using WHEN_CALLED, you specify the method that you'd like to change, inside the parenthesis. You can then decide when the behavior of future invocations that look like this be.
The different behaviors you can set for methods:
Verifying That Our Turtle Was Called
Now, let's use our fake Turtle to see if its method got called. We're doing to see if our code is working correctly with the Turtle class.
Here we used another macro of Isolator++ - ASSERT_WAS_CALLED(invocation).
This allows us to check, after the fact, that any method on our fake object was indeed called by our class under test.
If t->Forward() was not called on our fake class, then our test will fail.
It's that easy!