110-Fix-ClassFixture.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // 110-Fix-ClassFixture.cpp
  2. // Catch has two ways to express fixtures:
  3. // - Sections
  4. // - Traditional class-based fixtures (this file)
  5. // main() provided in 000-CatchMain.cpp
  6. #include <catch2/catch.hpp>
  7. class DBConnection
  8. {
  9. public:
  10. static DBConnection createConnection( std::string const & /*dbName*/ ) {
  11. return DBConnection();
  12. }
  13. bool executeSQL( std::string const & /*query*/, int const /*id*/, std::string const & arg ) {
  14. if ( arg.length() == 0 ) {
  15. throw std::logic_error("empty SQL query argument");
  16. }
  17. return true; // ok
  18. }
  19. };
  20. class UniqueTestsFixture
  21. {
  22. protected:
  23. UniqueTestsFixture()
  24. : conn( DBConnection::createConnection( "myDB" ) )
  25. {}
  26. int getID() {
  27. return ++uniqueID;
  28. }
  29. protected:
  30. DBConnection conn;
  31. private:
  32. static int uniqueID;
  33. };
  34. int UniqueTestsFixture::uniqueID = 0;
  35. TEST_CASE_METHOD( UniqueTestsFixture, "Create Employee/No Name", "[create]" ) {
  36. REQUIRE_THROWS( conn.executeSQL( "INSERT INTO employee (id, name) VALUES (?, ?)", getID(), "") );
  37. }
  38. TEST_CASE_METHOD( UniqueTestsFixture, "Create Employee/Normal", "[create]" ) {
  39. REQUIRE( conn.executeSQL( "INSERT INTO employee (id, name) VALUES (?, ?)", getID(), "Joe Bloggs" ) );
  40. }
  41. // Compile & run:
  42. // - g++ -std=c++11 -Wall -I$(CATCH_SINGLE_INCLUDE) -o 110-Fix-ClassFixture 110-Fix-ClassFixture.cpp 000-CatchMain.o && 110-Fix-ClassFixture --success
  43. // - cl -EHsc -I%CATCH_SINGLE_INCLUDE% 110-Fix-ClassFixture.cpp 000-CatchMain.obj && 110-Fix-ClassFixture --success
  44. // Expected compact output (all assertions):
  45. //
  46. // prompt> 110-Fix-ClassFixture.exe --reporter compact --success
  47. // 110-Fix-ClassFixture.cpp:47: passed: conn.executeSQL( "INSERT INTO employee (id, name) VALUES (?, ?)", getID(), "")
  48. // 110-Fix-ClassFixture.cpp:51: passed: conn.executeSQL( "INSERT INTO employee (id, name) VALUES (?, ?)", getID(), "Joe Bloggs" ) for: true
  49. // Passed both 2 test cases with 2 assertions.