mirror of
https://github.com/catchorg/Catch2.git
synced 2025-08-05 05:34:46 +02:00
Created Test fixtures (markdown)
28
Test-fixtures.md
Normal file
28
Test-fixtures.md
Normal file
@@ -0,0 +1,28 @@
|
||||
Sometimes you'll have the need to group a number of tests together and provide some context to that group of tests, for example an initial state or some shared variable. This is done by using a test fixture. In Catch, you define the test fixture as a simple structure:
|
||||
|
||||
```c++
|
||||
class UniqueTestsFixture {
|
||||
private:
|
||||
static int uniqueID;
|
||||
protected:
|
||||
DBConnection conn;
|
||||
public:
|
||||
UniqueTestsFixture() : conn(DBConnection::createConnection("myDB")) {
|
||||
}
|
||||
protected:
|
||||
int getID() {
|
||||
return ++uniqueID;
|
||||
}
|
||||
};
|
||||
|
||||
int UniqueTestsFixture::uniqueID = 0;
|
||||
|
||||
TEST_CASE_METHOD(UniqueTestsFixture, "Create Employee/No Name", "[create]") {
|
||||
REQUIRE_THROWS(conn.executeSQL("INSERT INTO employee (id, name) VALUES (?, ?)", getID(), ""));
|
||||
}
|
||||
TEST_CASE_METHOD(UniqueTestsFixture, "Create Employee/Normal", "[create]") {
|
||||
REQUIRE(conn.executeSQL("INSERT INTO employee (id, name) VALUES (?, ?)", getID(), "Joe Bloggs"));
|
||||
}
|
||||
```
|
||||
|
||||
The two test cases here will create uniquely-named derived classes of UniqueTestsFixture and thus can access the `getID()` protected method and `conn` member variables. This ensures that both the test cases are able to create a DBConnection using the same method (DRY principle) and that any ID's created are unique such that the order that tests are executed does not matter.
|
Reference in New Issue
Block a user