/ externals / catch / examples / 110-Fix-ClassFixture.cpp
110-Fix-ClassFixture.cpp
 1  
 2  //              Copyright Catch2 Authors
 3  // Distributed under the Boost Software License, Version 1.0.
 4  //   (See accompanying file LICENSE.txt or copy at
 5  //        https://www.boost.org/LICENSE_1_0.txt)
 6  
 7  // SPDX-License-Identifier: BSL-1.0
 8  
 9  // 110-Fix-ClassFixture.cpp
10  
11  // Catch has two ways to express fixtures:
12  // - Sections
13  // - Traditional class-based fixtures (this file)
14  
15  // main() provided by linkage to Catch2WithMain
16  
17  #include <catch2/catch_test_macros.hpp>
18  
19  class DBConnection
20  {
21  public:
22      static DBConnection createConnection( std::string const & /*dbName*/ ) {
23          return DBConnection();
24      }
25  
26      bool executeSQL( std::string const & /*query*/, int const /*id*/, std::string const & arg ) {
27          if ( arg.length() == 0 ) {
28              throw std::logic_error("empty SQL query argument");
29          }
30          return true; // ok
31      }
32  };
33  
34  class UniqueTestsFixture
35  {
36  protected:
37      UniqueTestsFixture()
38      : conn( DBConnection::createConnection( "myDB" ) )
39      {}
40  
41      int getID() {
42          return ++uniqueID;
43      }
44  
45  protected:
46      DBConnection conn;
47  
48  private:
49      static int uniqueID;
50  };
51  
52  int UniqueTestsFixture::uniqueID = 0;
53  
54  TEST_CASE_METHOD( UniqueTestsFixture, "Create Employee/No Name", "[create]" ) {
55      REQUIRE_THROWS( conn.executeSQL( "INSERT INTO employee (id, name) VALUES (?, ?)", getID(), "") );
56  }
57  
58  TEST_CASE_METHOD( UniqueTestsFixture, "Create Employee/Normal", "[create]" ) {
59      REQUIRE( conn.executeSQL( "INSERT INTO employee (id, name) VALUES (?, ?)", getID(), "Joe Bloggs" ) );
60  }
61  
62  // Compile & run:
63  // - g++ -std=c++14 -Wall -I$(CATCH_SINGLE_INCLUDE) -o 110-Fix-ClassFixture 110-Fix-ClassFixture.cpp && 110-Fix-ClassFixture --success
64  // - cl -EHsc -I%CATCH_SINGLE_INCLUDE% 110-Fix-ClassFixture.cpp && 110-Fix-ClassFixture --success
65  //
66  // Compile with pkg-config:
67  // - 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)
68  
69  // Expected compact output (all assertions):
70  //
71  // prompt> 110-Fix-ClassFixture.exe --reporter compact --success
72  // 110-Fix-ClassFixture.cpp:47: passed: conn.executeSQL( "INSERT INTO employee (id, name) VALUES (?, ?)", getID(), "")
73  // 110-Fix-ClassFixture.cpp:51: passed: conn.executeSQL( "INSERT INTO employee (id, name) VALUES (?, ?)", getID(), "Joe Bloggs" ) for: true
74  // Passed both 2 test cases with 2 assertions.