doctest

FORK: The fastest feature-rich C++11/14/17/20 single-header testing framework
git clone https://git.neptards.moe/neptards/doctest.git
Log | Files | Refs | README

testcases.md (8481B)


      1 ## Test cases
      2 
      3 While **doctest** fully supports the traditional, xUnit, style of class-based fixtures containing test case methods this is not the preferred style. Instead **doctest** provides a powerful mechanism for nesting subcases within a test case. For a more detailed discussion and examples see the [**tutorial**](tutorial.md#test-cases-and-subcases).
      4 
      5 Test cases and subcases are very easy to use in practice:
      6 
      7 * **TEST_CASE(** _test name_ **)**
      8 * **SUBCASE(** _subcase name_ **)**
      9 
     10 _test name_ and _subcase name_ are free form, quoted, strings. Test names don't have to be unique within the **doctest** executable. They should also be string literals.
     11 
     12 It is possible to write test cases inside of class bodies in C++17 with the help of ```TEST_CASE_CLASS()``` - used just like ```TEST_CASE()``` - making testing private parts of classes easier.
     13 
     14 Keep in mind that even though **doctest** is [**thread-safe**](faq.md#is-doctest-thread-aware) - using subcases has to be done only in the main test runner thread.
     15 
     16 Test cases can also be parameterized - see the [**documentation**](parameterized-tests.md)
     17 
     18 Test cases and subcases can be filtered through the use of the [**command line**](commandline.md)
     19 
     20 ## BDD-style test cases
     21 
     22 In addition to **doctest**'s take on the classic style of test cases, **doctest** supports an alternative syntax that allow tests to be written as "executable specifications" (one of the early goals of [Behaviour Driven Development](http://dannorth.net/introducing-bdd/)). This set of macros map on to ```TEST_CASE```s and ```SUBCASE```s, with a little internal support to make them smoother to work with.
     23 
     24 * **SCENARIO(** _scenario name_ **)**
     25 
     26 This macro maps onto ```TEST_CASE``` and works in the same way, except that the test case name will be prefixed by "Scenario: "
     27 
     28 * **SCENARIO_TEMPLATE(** _scenario name_, _type_, _list of types_ **)**
     29 
     30 This macro maps onto ```TEST_CASE_TEMPLATE``` and works in the same way, except that the test case name will be prefixed by "Scenario: "
     31 
     32 * **SCENARIO_TEMPLATE_DEFINE(** _scenario name_, _type_, _id_ **)**
     33 
     34 This macro maps onto ```TEST_CASE_TEMPLATE_DEFINE``` and works in the same way, except that the test case name will be prefixed by "Scenario: "
     35 
     36 * **GIVEN(** _something_ **)**
     37 * **WHEN(** _something_ **)**
     38 * **THEN(** _something_ **)**
     39 
     40 These macros map onto ```SUBCASE```s except that the subcase names are the _something_s prefixed by "given: ", "when: " or "then: " respectively.
     41 
     42 * **AND_WHEN(** _something_ **)**
     43 * **AND_THEN(** _something_ **)**
     44 
     45 Similar to ```WHEN``` and ```THEN``` except that the prefixes start with "and ". These are used to chain ```WHEN```s and ```THEN```s together.
     46 
     47 When any of these macros are used the console reporter recognises them and formats the test case header such that the Givens, Whens and Thens are aligned to aid readability.
     48 
     49 Other than the additional prefixes and the formatting in the console reporter these macros behave exactly as ```TEST_CASE```s and ```SUBCASE```s. As such there is nothing enforcing the correct sequencing of these macros - that's up to the programmer!
     50 
     51 Note that when using the [`--test-case=<filters>`](https://github.com/doctest/doctest/blob/master/doc/markdown/commandline.md) command line option (or `--subcase=<filters>`) you will have to pass the prefix `Scenario: ` as well.
     52 
     53 ## Test fixtures
     54 
     55 Although **doctest** allows you to group tests together as subcases within a test case, it can still be convenient, sometimes, to group them using a more traditional test fixture. **doctest** fully supports this too. You define the test fixture as a simple structure:
     56 
     57 ```c++
     58 class UniqueTestsFixture {
     59 private:
     60     static int uniqueID;
     61 protected:
     62     DBConnection conn;
     63 public:
     64     UniqueTestsFixture() : conn(DBConnection::createConnection("myDB")) {}
     65 protected:
     66     int getID() {
     67         return ++uniqueID;
     68     }
     69 };
     70 
     71 int UniqueTestsFixture::uniqueID = 0;
     72 
     73 TEST_CASE_FIXTURE(UniqueTestsFixture, "Create Employee/No Name") {
     74     REQUIRE_THROWS(conn.executeSQL("INSERT INTO employee (id, name) VALUES (?, ?)", getID(), ""));
     75 }
     76 TEST_CASE_FIXTURE(UniqueTestsFixture, "Create Employee/Normal") {
     77     REQUIRE(conn.executeSQL("INSERT INTO employee (id, name) VALUES (?, ?)", getID(), "Joe Bloggs"));
     78 }
     79 ```
     80 
     81 The two test cases here will create uniquely-named derived classes of UniqueTestsFixture and thus can access the `getID()` protected method and `conn` member variables. This ensures that both the test cases are able to create a DBConnection using the same method (DRY principle) and that any ID's created are unique such that the order that tests are executed does not matter.
     82 
     83 ## Test suites
     84 
     85 Test cases can be grouped into test suites. This is done with ```TEST_SUITE()``` or ```TEST_SUITE_BEGIN()``` / ```TEST_SUITE_END()```.
     86 
     87 For example:
     88 
     89 ```c++
     90 TEST_CASE("") {} // not part of any test suite
     91 
     92 TEST_SUITE("math") {
     93     TEST_CASE("") {} // part of the math test suite
     94     TEST_CASE("") {} // part of the math test suite
     95 }
     96 
     97 TEST_SUITE_BEGIN("utils");
     98 
     99 TEST_CASE("") {} // part of the utils test suite
    100 
    101 TEST_SUITE_END();
    102 
    103 TEST_CASE("") {} // not part of any test suite
    104 ```
    105 
    106 Then test cases from specific test suites can be executed with the help of filters - check out the [**command line**](commandline.md)
    107 
    108 ## Decorators
    109 
    110 Test cases can be *decorated* with additional attributes like this:
    111 
    112 ```c++
    113 TEST_CASE("name"
    114           * doctest::description("shouldn't take more than 500ms")
    115           * doctest::timeout(0.5)) {
    116     // asserts
    117 }
    118 ```
    119 
    120 Multiple decorators can be used at the same time. These are the currently supported decorators:
    121 
    122 - **```skip(bool = true)```** - marks the test case to be skipped from execution - unless the ```--no-skip``` option is used
    123 - **```no_breaks(bool = true)```** - no breaking into the debugger for asserts in the test case - useful in combination with `may_fail`/`should_fail`/`expected_failures`
    124 - **```no_output(bool = true)```** - no output from asserts in the test case - useful in combination with `may_fail`/`should_fail`/`expected_failures`
    125 - **```may_fail(bool = true)```** - doesn't fail the test if any given assertion fails (but still reports it) - this can be useful to flag a work-in-progress, or a known issue that you don't want to immediately fix but still want to track in the your tests
    126 - **```should_fail(bool = true)```** - like **```may_fail()```** but fails the test if it passes - this can be useful if you want to be notified of accidental, or third-party, fixes
    127 - **```expected_failures(int)```** - defines the number of assertions that are expected to fail within the test case - reported as failure when the number of failed assertions is different than the declared expected number of failures
    128 - **```timeout(double)```** - fails the test case if its execution exceeds this limit (in seconds) - but doesn't terminate it - that would require subprocess support
    129 - **```test_suite("name")```** - can be used on test cases to override (or just set) the test suite they are in
    130 - **```description("text")```** - a description of the test case
    131 
    132 The values that the decorators take are computed while registering the test cases (during global initialization) - before entering ```main()``` and not just before running them.
    133 
    134 Decorators can also be applied to test suite blocks and all test cases in that block inherit them:
    135 
    136 ```c++
    137 TEST_SUITE("some TS" * doctest::description("all tests will have this")) {
    138     TEST_CASE("has a description from the surrounding test suite") {
    139         // asserts
    140     }
    141 }
    142 TEST_SUITE("some TS") {
    143     TEST_CASE("no description even though in the same test suite as the one above") {
    144         // asserts
    145     }
    146 }
    147 ```
    148 
    149 Test cases can override the decorators that they inherit from their surrounding test suite:
    150 
    151 ```c++
    152 TEST_SUITE("not longer than 500ms" * doctest::timeout(0.5)) {
    153     TEST_CASE("500ms limit") {
    154         // asserts
    155     }
    156     TEST_CASE("200ms limit" * doctest::timeout(0.2)) {
    157         // asserts
    158     }
    159 }
    160 ```
    161 
    162 ------
    163 
    164 - Check out the [**subcases and BDD example**](../../examples/all_features/subcases.cpp)
    165 - Check out the [**assertion macros example**](../../examples/all_features/assertion_macros.cpp) to see how test suites are used
    166 - Tests are registered from top to bottom of each processed cpp after the headers have been preprocessed and included but there is no ordering between cpp files.
    167 
    168 ---------------
    169 
    170 [Home](readme.md#reference)
    171 
    172 <p align="center"><img src="../../scripts/data/logo/icon_2.svg"></p>