110-Fix-ClassFixture.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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 by linkage to Catch2WithMain
  6. #include <catch2/catch_test_macros.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++14 -Wall -I$(CATCH_SINGLE_INCLUDE) -o 110-Fix-ClassFixture 110-Fix-ClassFixture.cpp && 110-Fix-ClassFixture --success
  43. // - cl -EHsc -I%CATCH_SINGLE_INCLUDE% 110-Fix-ClassFixture.cpp && 110-Fix-ClassFixture --success
  44. //
  45. // Compile with pkg-config:
  46. // - g++ -std=c++14 -Wall $(pkg-config catch2-with-main --cflags) -o 110-Fix-ClassFixture 110-Fix-ClassFixture.cpp $(pkg-config catch2-with-main --libs)
  47. // Expected compact output (all assertions):
  48. //
  49. // prompt> 110-Fix-ClassFixture.exe --reporter compact --success
  50. // 110-Fix-ClassFixture.cpp:47: passed: conn.executeSQL( "INSERT INTO employee (id, name) VALUES (?, ?)", getID(), "")
  51. // 110-Fix-ClassFixture.cpp:51: passed: conn.executeSQL( "INSERT INTO employee (id, name) VALUES (?, ?)", getID(), "Joe Bloggs" ) for: true
  52. // Passed both 2 test cases with 2 assertions.