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