Chapter 11 Exercise Set 1: Doctest Exercises

  1. Given the file test_times.cpp below, create files Time.h and Time.cpp that will make the tests pass.

    #define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN
    #include <doctest.h>
    #include "Time.h"
    using namespace std;
    
    TEST_CASE("Test can create and render Times") {
        Time t1;
        CHECK(t1.to_string() == "0:00:00");
        Time t2(7);
        CHECK(t2.to_string() == "0:00:07");
        Time t3(72);
        CHECK(t3.to_string() == "0:01:12");
        Time t4(7 * 3600 + 11 * 60 + 19);
        CHECK(t4.to_string() == "7:11:19");
    }
    
  2. Add the following test case, and make it pass:

    TEST_CASE("Test hour-minute and hour-minute-second constructors") {
        Time t1(5, 37);
        CHECK(t1.to_string() == "5:37:00");
        Time t2(7, 2, 11);
        CHECK(t2.to_string() == "7:02:11");
    }
    
  3. Now use operating overloading on this one:

    TEST_CASE("Test can add two Times with + operator") {
        Time t1(25, 40);
        Time t2(17, 2, 42);
        Time t3 = t1 + t2;
        CHECK(t3.to_string() == "42:42:42");
    }
    
  4. Try overloading the stream insertion operator << as was done in the chapter for Point objects for Times. This will be easier for us to test “by hand”, so when you have successfully completed this task, the following hand_test_times.cpp should compile and run as expected:

    #include <iostream>
    #include <string>
    #include "Time.h"
    using namespace std;
    
    int main() {
        Time t(3600 * 4 + 60 * 11 + 22);
        cout << "Time t is: " << t << endl;
        // should print 4:11:22
    
        return 0;
    }
    
  5. The following test_points.cpp file contains three test cases. You should add these test cases one at a time to your version of the file, writing scaffolding so they compile, and then adding code to make the test pass.

    #define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN
    #include <doctest.h>
    #include <iostream>
    #include <string>
    #include "Point.h"
    using namespace std;
    
    TEST_CASE("Test can create Points") {
        Point p1;
        CHECK(p1.x == 0.0);
        CHECK(p1.y == 0.0);
        Point p2(3, 4);
        CHECK(p2.x == 3.0);
        CHECK(p2.y == 4.0);
    }
    
    TEST_CASE("Test can add Points") {
        Point p1(3, 4);
        Point p2(5, 2);
        Point p3 = p1 + p2;
        CHECK(p3.x == 8.0);
        CHECK(p3.y == 6.0);
    }
    
    TEST_CASE("Test can render Points as strings") {
        Point p(8, 7);
        string expected = "(8.000000, 7.000000)";
        CHECK(p.to_string() == expected);
    }