Lesson 4: Working With Stubs
C++Test uses stub functions when a method being tested calls an external function that is not available or accessible. Rather than actually calling the function, C++Test calls the stub and uses the return values that the stub provides.
If C++Test creates a stub for an external function but you would rather use the actual external function, you can have C++Test use that original function by changing the stub type and telling C++Test where the original function is located.
C++Test always creates stubs when the method under test calls an external function that is unavailable or inaccessible. When a C++Test generated stub is called, it returns 0 or NULL by default; if you want to control what return values are used, you can create a stub table that specifies what outcome should be used for a certain input.
Stub Tables
For an example of how to create a stub table, open ex02.cpp (in <C++Test_install_dir>/examples), build a test executable for it, then perform the following steps:
- Open the Stub Tables tab.
- Select the bool odd(int) function.
- Specify what outcome you want returned for a certain input. For example, in this case you might want to have an input of "0" and an outcome of "false". Enter one such input/outcome correlation, then click Add Test Case to add this entry to your stub table.
- Specify additional input/outcome correlations. For example, you might want to enter the following input/outcome correlations:
- input: 5; outcome: true
- input: 99; outcome: true
When C++Test calls this function, it will use these input/outcome correlations.
User-Defined Stubs
You can also have C++Test call user-defined stubs instead of calling any actual function or C++Test-generated function. User-defined stubs can be entered by performing the following steps:
- Double-click the appropriate row in the Stub Table's Function column.
- Your selected editor will open with an empty stub file. The empty stub file will look something like this:
/*
* DO NOT CHANGE THE SIGNATURE OF THIS METHOD - JUST FILL ITS BODY
* Signature for:
* bool odd(int)
*/
bool _ModuleTest_UStub_odd(int)
{
}
- Add code to the function. You can provide names for the parameters (if you intend to use them). Do not change the name or signature of the function, and always return the proper type.
- Save the code in your editor.
- In the bottom of the Stub Tables tab, click the User Defined option.
|