class MyTestCase : public Pt::Unit::TestCase { public: MyTestCase() : Pt::Unit::TestCase("MyTestCase") , _a(0), _b(0) { } void setUp() { _a = 5; _b = 5; } void tearDown() { } void test() { _a += _b; PT_UNIT_ASSERT(_a == 10); } private: int _a; int _b; };
PtUnitTest mytest : mytest.cpp ;
This will cause the jam tool to report a failed build if the Unit test does not run through, which is the desired behaviour. This way Unit tests can easily be integrated in automated builds.
class MyTestSuite { public: MyTestSuite() : Pt::Unit::TestSuite("MyTestSuite") { this->registerMethod("AdditionTest", *this, &MyTestSuite::AdditionTest); } void AdditionTest(int a, int b) { // testing code } };
A protocol can then by used to call the AdditionTest method multiple times with different data. For convenience, such a protocol is included in the Unit test module already and is called TestSchedule. Here we can assign data to tests.
class MyTestSchedule : public Pt::Unit::TestSchedule { public: MyTestSchedule() , _first(1, 1) , _second(2, 2) , _three(3, 3) { this->includeTest("AdditionTest", _first); this->includeTest("AdditionTest", _second); this->includeTest("AdditionTest", _third); } private: Args _first; Args _second; Args _third; };
When this protocol is applied to MyTestSuite, the AdditionTest will be called three times with different test data. It is very possible to read data from a file or another data source.
#include <Pt/Unit/TestProtocol.h> #include <Pt/System/Process.h> class MyProtocol : public Pt::Unit::TestProtocol { public: MyProtocol() {} void run(Pt::Unit::TestSuite& suite) { suite.runTest( "MyTest" ); Pt::System::Process::sleep(1000); suite.runTest( "MyTest" ); Pt::System::Process::sleep(1000); suite.runTest( "MyTest" ); } };
The protocol can then be applied to a TestSuite. The methods are resolved using object reflection. The TestSuite class requires that all runnable tests are registered for reflection. TestSuite inherits reflection capabilities from Pt::Reflectable. If a test can not be executed through the TestSuite::runTest method an exception of the type PtLogicError is thrown and the test fails if it is allowed to propagate. The new protocol can be assigned to a TestSuite in the constructor:
MyProtocol protocol; class MyTestSuite { public: MyTestSuite() : Pt::Unit::TestSuite("MyTestSuite", protocol) { this->registerMethod("MyTest", *this, &MyTestSuite::MyTest); } void MyTest() { // testing code } };
Alternatively, a protocol can be set using the Unit::TestSuite::setProtocol method. It is entirely possible to load and assign protocols at run-time.
int main() { Pt::Unit::Application app; std::ofstream fs("log.txt"); Pt::Unit::Reporter reporter(fs); app.setReporter(reporter); return app.run(); }
For convenience, the header file TestMain.h already contains such a main loop where reporters can be selected by command line arguments. So the implementor of a test only has to include TestMain.h in the file where be derives and registers the tests.