diff --git a/Tutorial.md b/Tutorial.md index f25aa87..86d45d4 100644 --- a/Tutorial.md +++ b/Tutorial.md @@ -14,4 +14,48 @@ The rest of this tutorial will assume that the CATCH root folder is available un # Writing tests -coming soon... \ No newline at end of file +Let's start with a really simple example. Say you have written a function to calculate factorials and now you want to test it. To keep things simple we'll put everything in a single file. + +```c++ + #include "catch_default_main.hpp" // This brings in a default implementation for main() + + unsigned int Factorial( unsigned int number ) + { + return number <= 1 ? number : Factorial(number-1)*number; + } + + TEST_CASE( "example/factorial", "The Factorial function should return the factorial of the number passed in" ) + { + REQUIRE( Factorial(0) == 0 ); + REQUIRE( Factorial(1) == 1 ); + REQUIRE( Factorial(2) == 2 ); + REQUIRE( Factorial(3) == 6 ); + REQUIRE( Factorial(10) == 3628800 ); + } +``` + +This will compile to a complete executable, which responds to command line parameters. If you just run it with no arguments it will execute all test cases (in this case there is just one), report any failures, report a summary of how many tests passed and failed and return the number of failed tests (useful for if you just want a yes/ no answer to: "did it work"). + +Now the more awake among you may notice that the Factorial function will hit problems when the return value starts to exceed the range of an unsigned int. With factorials that can happen quite quickly. Assuming 32-bit ints the maximum value is 4,294,967,295. +Let's add a few more test for this: + +```c++ + TEST_CASE( "example/factorial", "The Factorial function should return the factorial of the number passed in" ) + { + REQUIRE( Factorial(0) == 0 ); + REQUIRE( Factorial(1) == 1 ); + REQUIRE( Factorial(2) == 2 ); + REQUIRE( Factorial(3) == 6 ); + REQUIRE( Factorial(10) == 3628800 ); + REQUIRE( Factorial(12) == 479001600 ); + REQUIRE( Factorial(13) == 6227020800 ); + } +``` + +Your compiler will likely warn you about that last value (for 32 bit ints), but ignore that for now. Running this gives us this report: + + /Path/../example.cpp(16): Factorial(13) == 6227020800 failed for: 1932053504 == 6227020800 + +Note that we get the actual return value of Factorial(13) printed for us - even though we used a natural expression with the == operator. + +If we change the factorial function to take and return unsigned long instead (assuming 64 bit long) we should see this particular bug go away. Of course we have just pushed it out to a higher number, but it's up to the logic of your code to decide how to handle the overflow. \ No newline at end of file