cookbook.dox 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  1. /*! \page cppunit_cookbook CppUnit Cookbook
  2. Here is a short cookbook to help you get started.
  3. \section simple_test_case Simple Test Case
  4. You want to know whether your code is working.
  5. How do you do it?
  6. There are many ways. Stepping through a debugger or
  7. littering your code with stream output calls are two of
  8. the simpler ways, but they both have drawbacks.
  9. Stepping through your code is a good idea, but it
  10. is not automatic. You have to do it every time you
  11. make changes. Streaming out text is also fine,
  12. but it makes code ugly and it generates far more
  13. information than you need most of the time.
  14. Tests in %CppUnit can be run automatically.
  15. They are easy to set up and once you have
  16. written them, they are always there to help
  17. you keep confidence in the quality of your code.
  18. To make a simple test, here is what you do:
  19. Subclass the \link CppUnit::TestCase TestCase \endlink class.
  20. Override the method \link CppUnit::TestCase::runTest() runTest()\endlink.
  21. When you want to check a value, call
  22. \link CPPUNIT_ASSERT() CPPUNIT_ASSERT(bool) \endlink
  23. and pass in an expression that is true if the
  24. test succeeds.
  25. For example, to test the equality comparison
  26. for a Complex number class, write:
  27. \code
  28. class ComplexNumberTest : public CppUnit::TestCase {
  29. public:
  30. ComplexNumberTest( std::string name ) : CppUnit::TestCase( name ) {}
  31. void runTest() {
  32. CPPUNIT_ASSERT( Complex (10, 1) == Complex (10, 1) );
  33. CPPUNIT_ASSERT( !(Complex (1, 1) == Complex (2, 2)) );
  34. }
  35. };
  36. \endcode
  37. That was a very simple test. Ordinarily,
  38. you'll have many little test cases that you'll
  39. want to run on the same set of objects. To do
  40. this, use a fixture.
  41. \section fixture Fixture
  42. A fixture is a known set of objects that
  43. serves as a base for a set of test cases.
  44. Fixtures come in very handy when you are
  45. testing as you develop.
  46. Let's try out this style of development and
  47. learn about fixtures along the away. Suppose
  48. that we are really developing a complex
  49. number class. Let's start by defining a
  50. empty class named Complex.
  51. \code
  52. class Complex {};
  53. \endcode
  54. Now create an instance of ComplexNumberTest
  55. above, compile the code and see what happens.
  56. The first thing we notice is a few compiler
  57. errors. The test uses <tt>operator ==</tt>, but it is
  58. not defined. Let's fix that.
  59. \code
  60. bool operator==( const Complex &a, const Complex &b)
  61. {
  62. return true;
  63. }
  64. \endcode
  65. Now compile the test, and run it. This time it
  66. compiles but the test fails.
  67. We need a bit more to get an <tt>operator ==</tt>working
  68. correctly, so we revisit the code.
  69. \code
  70. class Complex {
  71. friend bool operator ==(const Complex& a, const Complex& b);
  72. double real, imaginary;
  73. public:
  74. Complex( double r, double i = 0 )
  75. : real(r)
  76. , imaginary(i)
  77. {
  78. }
  79. };
  80. bool operator ==( const Complex &a, const Complex &b )
  81. {
  82. return a.real == b.real && a.imaginary == b.imaginary;
  83. }
  84. \endcode
  85. If we compile now and run our test it will pass.
  86. Now we are ready to add new operations and
  87. new tests. At this point a fixture would be
  88. handy. We would probably be better off when
  89. doing our tests if we decided to instantiate
  90. three or four complex numbers and reuse them
  91. across our tests.
  92. Here is how we do it:
  93. - Add member variables for each part of the
  94. \link CppUnit::TestFixture fixture \endlink
  95. - Override \link CppUnit::TestFixture::setUp() setUp() \endlink
  96. to initialize the variables
  97. - Override \link CppUnit::TestFixture::tearDown() tearDown() \endlink
  98. to release any permanent resources you allocated in
  99. \link CppUnit::TestFixture::setUp() setUp() \endlink
  100. \code
  101. class ComplexNumberTest : public CppUnit::TestFixture {
  102. private:
  103. Complex *m_10_1, *m_1_1, *m_11_2;
  104. public:
  105. void setUp()
  106. {
  107. m_10_1 = new Complex( 10, 1 );
  108. m_1_1 = new Complex( 1, 1 );
  109. m_11_2 = new Complex( 11, 2 );
  110. }
  111. void tearDown()
  112. {
  113. delete m_10_1;
  114. delete m_1_1;
  115. delete m_11_2;
  116. }
  117. };
  118. \endcode
  119. Once we have this fixture, we can add the complex
  120. addition test case and any others that we need
  121. over the course of our development.
  122. \section test_case Test Case
  123. How do you write and invoke individual tests using a fixture?
  124. There are two steps to this process:
  125. - Write the test case as a method in the fixture class
  126. - Create a TestCaller which runs that particular method
  127. Here is our test case class with a few extra case methods:
  128. \code
  129. class ComplexNumberTest : public CppUnit::TestFixture {
  130. private:
  131. Complex *m_10_1, *m_1_1, *m_11_2;
  132. public:
  133. void setUp()
  134. {
  135. m_10_1 = new Complex( 10, 1 );
  136. m_1_1 = new Complex( 1, 1 );
  137. m_11_2 = new Complex( 11, 2 );
  138. }
  139. void tearDown()
  140. {
  141. delete m_10_1;
  142. delete m_1_1;
  143. delete m_11_2;
  144. }
  145. void testEquality()
  146. {
  147. CPPUNIT_ASSERT( *m_10_1 == *m_10_1 );
  148. CPPUNIT_ASSERT( !(*m_10_1 == *m_11_2) );
  149. }
  150. void testAddition()
  151. {
  152. CPPUNIT_ASSERT( *m_10_1 + *m_1_1 == *m_11_2 );
  153. }
  154. };
  155. \endcode
  156. One may create and run instances for each test case like this:
  157. \code
  158. CppUnit::TestCaller<ComplexNumberTest> test( "testEquality",
  159. &ComplexNumberTest::testEquality );
  160. CppUnit::TestResult result;
  161. test.run( &result );
  162. \endcode
  163. The second argument to the test caller constructor is the address of
  164. a method on ComplexNumberTest. When the test caller is run,
  165. that specific method will be run. This is not a useful thing to do,
  166. however, as no diagnostics will be displayed.
  167. One will normally use a \link ExecutingTest TestRunner \endlink (see below)
  168. to display the results.
  169. Once you have several tests, organize them into a suite.
  170. \section suite Suite
  171. How do you set up your tests so that you can run them all at once?
  172. %CppUnit provides a \link CppUnit::TestSuite TestSuite \endlink class
  173. that runs any number of TestCases together.
  174. We saw, above, how to run a single test case.
  175. To create a suite of two or more tests, you do the following:
  176. \code
  177. CppUnit::TestSuite suite;
  178. CppUnit::TestResult result;
  179. suite.addTest( new CppUnit::TestCaller<ComplexNumberTest>(
  180. "testEquality",
  181. &ComplexNumberTest::testEquality ) );
  182. suite.addTest( new CppUnit::TestCaller<ComplexNumberTest>(
  183. "testAddition",
  184. &ComplexNumberTest::testAddition ) );
  185. suite.run( &result );
  186. \endcode
  187. \link CppUnit::TestSuite TestSuites \endlink don't only have to
  188. contain callers for TestCases. They can contain any object
  189. that implements the \link CppUnit::Test Test \endlink interface.
  190. For example, you can create a
  191. \link CppUnit::TestSuite TestSuite \endlink in your code and
  192. I can create one in mine, and we can run them together
  193. by creating a \link CppUnit::TestSuite TestSuite \endlink
  194. that contains both:
  195. \code
  196. CppUnit::TestSuite suite;
  197. CppUnit::TestResult result;
  198. suite.addTest( ComplexNumberTest::suite() );
  199. suite.addTest( SurrealNumberTest::suite() );
  200. suite.run( &result );
  201. \endcode
  202. \section test_runner TestRunner
  203. How do you run your tests and collect their results?
  204. Once you have a test suite, you'll want to run it. %CppUnit provides tools
  205. to define the suite to be run and to display its results.
  206. You make your suite accessible to a \link ExecutingTest TestRunner \endlink
  207. program with a static method <I>suite</I> that returns a test suite.
  208. For example, to make a ComplexNumberTest suite available to a
  209. \link ExecutingTest TestRunner \endlink, add the following code to
  210. ComplexNumberTest:
  211. \code
  212. public:
  213. static CppUnit::TestSuite *suite()
  214. {
  215. CppUnit::TestSuite *suiteOfTests = new CppUnit::TestSuite( "ComplexNumberTest" );
  216. suiteOfTests->addTest( new CppUnit::TestCaller<ComplexNumberTest>(
  217. "testEquality",
  218. &ComplexNumberTest::testEquality ) );
  219. suiteOfTests->addTest( new CppUnit::TestCaller<ComplexNumberTest>(
  220. "testAddition",
  221. &ComplexNumberTest::testAddition ) );
  222. return suiteOfTests;
  223. }
  224. \endcode
  225. \anchor test_runner_code
  226. To use the text version, include the header files for the tests in Main.cpp:
  227. \code
  228. #include <cppunit/ui/text/TestRunner.h>
  229. #include "ExampleTestCase.h"
  230. #include "ComplexNumberTest.h"
  231. \endcode
  232. And add a call to
  233. \link ::CppUnit::TextUi::TestRunner::addTest addTest(CppUnit::Test *) \endlink
  234. in the <tt>main()</tt> function:
  235. \code
  236. int main( int argc, char **argv)
  237. {
  238. CppUnit::TextUi::TestRunner runner;
  239. runner.addTest( ExampleTestCase::suite() );
  240. runner.addTest( ComplexNumberTest::suite() );
  241. runner.run();
  242. return 0;
  243. }
  244. \endcode
  245. The \link ExecutingTest TestRunner \endlink will run the tests.
  246. If all the tests pass, you'll get an informative message.
  247. If any fail, you'll get the following information:
  248. - The name of the test case that failed
  249. - The name of the source file that contains the test
  250. - The line number where the failure occurred
  251. - All of the text inside the call to CPPUNIT_ASSERT() which detected the failure
  252. %CppUnit distinguishes between <I>failures</I> and <I>errors</I>. A failure is
  253. anticipated and checked for with assertions. Errors are unanticipated problems
  254. like division by zero and other exceptions thrown by the C++ runtime or your code.
  255. \section helper_macros Helper Macros
  256. As you might have noticed, implementing the fixture static <tt>suite()</tt>
  257. method is a repetitive and error prone task. A \ref WritingTestFixture set of
  258. macros have been created to automatically implements the
  259. static <tt>suite()</tt> method.
  260. The following code is a rewrite of ComplexNumberTest using those macros:
  261. \code
  262. #include <cppunit/extensions/HelperMacros.h>
  263. class ComplexNumberTest : public CppUnit::TestFixture {
  264. \endcode
  265. First, we declare the suite, passing the class name to the macro:
  266. \code
  267. CPPUNIT_TEST_SUITE( ComplexNumberTest );
  268. \endcode
  269. The suite created by the static <tt>suite()</tt> method is named after
  270. the class name.
  271. Then, we declare each test case of the fixture:
  272. \code
  273. CPPUNIT_TEST( testEquality );
  274. CPPUNIT_TEST( testAddition );
  275. \endcode
  276. Finally, we end the suite declaration:
  277. \code
  278. CPPUNIT_TEST_SUITE_END();
  279. \endcode
  280. At this point, a method with the following signature has been implemented:
  281. \code
  282. static CppUnit::TestSuite *suite();
  283. \endcode
  284. The rest of the fixture is left unchanged:
  285. \code
  286. private:
  287. Complex *m_10_1, *m_1_1, *m_11_2;
  288. public:
  289. void setUp()
  290. {
  291. m_10_1 = new Complex( 10, 1 );
  292. m_1_1 = new Complex( 1, 1 );
  293. m_11_2 = new Complex( 11, 2 );
  294. }
  295. void tearDown()
  296. {
  297. delete m_10_1;
  298. delete m_1_1;
  299. delete m_11_2;
  300. }
  301. void testEquality()
  302. {
  303. CPPUNIT_ASSERT( *m_10_1 == *m_10_1 );
  304. CPPUNIT_ASSERT( !(*m_10_1 == *m_11_2) );
  305. }
  306. void testAddition()
  307. {
  308. CPPUNIT_ASSERT( *m_10_1 + *m_1_1 == *m_11_2 );
  309. }
  310. };
  311. \endcode
  312. The name of the \link CppUnit::TestCaller TestCaller \endlink added to the
  313. suite are a composition of the fixture name and the method name.
  314. In the present case, the names would be:
  315. "ComplexNumberTest.testEquality" and "ComplexNumberTest.testAddition".
  316. The \link WritingTestFixture helper macros \endlink help you write comon assertion.
  317. For example, to check that ComplexNumber throws a MathException when dividing
  318. a number by 0:
  319. - add the test to the suite using CPPUNIT_TEST_EXCEPTION, specifying the expected
  320. exception type.
  321. - write the test case method
  322. \code
  323. CPPUNIT_TEST_SUITE( ComplexNumberTest );
  324. // [...]
  325. CPPUNIT_TEST_EXCEPTION( testDivideByZeroThrows, MathException );
  326. CPPUNIT_TEST_SUITE_END();
  327. // [...]
  328. void testDivideByZeroThrows()
  329. {
  330. // The following line should throw a MathException.
  331. *m_10_1 / ComplexNumber(0);
  332. }
  333. \endcode
  334. If the expected exception is not thrown, then a assertion failure is reported.
  335. \section test_factory_registry TestFactoryRegistry
  336. The TestFactoryRegistry was created to solve two pitfalls:
  337. - forgetting to add your fixture suite to the test runner (since it is in
  338. another file, it is easy to forget)
  339. - compilation bottleneck caused by the inclusion of all test case headers
  340. (see \ref test_runner_code "previous example")
  341. The TestFactoryRegistry is a place where suites can be registered at initialization
  342. time.
  343. To register the ComplexNumber suite, in the .cpp file, you add:
  344. \code
  345. #include <cppunit/extensions/HelperMacros.h>
  346. CPPUNIT_TEST_SUITE_REGISTRATION( ComplexNumberTest );
  347. \endcode
  348. Behind the scene, a static variable type of
  349. \link CppUnit::AutoRegisterSuite AutoRegisterSuite \endlink is declared.
  350. On construction, it will
  351. \link CppUnit::TestFactoryRegistry::registerFactory(TestFactory*) register \endlink
  352. a \link CppUnit::TestSuiteFactory TestSuiteFactory \endlink into the
  353. \link CppUnit::TestFactoryRegistry TestFactoryRegistry \endlink.
  354. The \link CppUnit::TestSuiteFactory TestSuiteFactory \endlink returns
  355. the \link CppUnit::TestSuite TestSuite \endlink returned by ComplexNumber::suite().
  356. To run the tests, using the text test runner, we don't need to include the fixture
  357. anymore:
  358. \code
  359. #include <cppunit/extensions/TestFactoryRegistry.h>
  360. #include <cppunit/ui/text/TestRunner.h>
  361. int main( int argc, char **argv)
  362. {
  363. CppUnit::TextUi::TestRunner runner;
  364. \endcode
  365. First, we retreive the instance of the
  366. \link CppUnit::TestFactoryRegistry TestFactoryRegistry \endlink:
  367. \code
  368. CppUnit::TestFactoryRegistry &registry = CppUnit::TestFactoryRegistry::getRegistry();
  369. \endcode
  370. Then, we obtain and add a new \link CppUnit::TestSuite TestSuite \endlink created
  371. by the \link CppUnit::TestFactoryRegistry TestFactoryRegistry \endlink that
  372. contains all the test suite registered using CPPUNIT_TEST_SUITE_REGISTRATION().
  373. \code
  374. runner.addTest( registry.makeTest() );
  375. runner.run();
  376. return 0;
  377. }
  378. \endcode
  379. \section post_build_check Post-build check
  380. Well, now that we have our unit tests running, how about integrating unit
  381. testing to our build process ?
  382. To do that, the application must returns a value different than 0 to indicate that
  383. there was an error.
  384. \link CppUnit::TextUi::TestRunner::run() TestRunner::run() \endlink returns
  385. a boolean indicating if the run was successful.
  386. Updating our main programm, we obtains:
  387. \code
  388. #include <cppunit/extensions/TestFactoryRegistry.h>
  389. #include <cppunit/ui/text/TestRunner.h>
  390. int main( int argc, char **argv)
  391. {
  392. CppUnit::TextUi::TestRunner runner;
  393. CppUnit::TestFactoryRegistry &registry = CppUnit::TestFactoryRegistry::getRegistry();
  394. runner.addTest( registry.makeTest() );
  395. bool wasSuccessful = runner.run( "", false );
  396. return !wasSuccessful;
  397. }
  398. \endcode
  399. Now, you need to run your application after compilation.
  400. With Visual C++, this is done in <em>Project Settings/Post-Build step</em>,
  401. by adding the following command: <tt>"$(TargetPath)"</tt>. It is expanded to
  402. the application executable path. Look up the project
  403. <tt>examples/cppunittest/CppUnitTestMain.dsp</tt> which
  404. use that technic.
  405. Original version by Michael Feathers.
  406. Doxygen conversion and update by Baptiste Lepilleur.
  407. */