有很多方法可以给这只猫剥皮。
下面给出了一个易于配置的示例......(警告:前面的伪代码)
void Tester::LoadTestTuples(QString filename)
{
// ... open file
while(fileHandle.ok())
{
fileHandle >> a >> b >> c >> expectedResult;
// this is your own test data file - all tuples are expected to be read.
QCOMPARE(TestAddFunction(a, b, c), expectedResult);
}
}
并这样做:
$ touch testData.txt
$ echo "1 4 5 10" >> testData.txt
在内部,我们更喜欢将 testData.txt 添加到 qrc 文件并编译它,但这是首选。
您可以扩展它以提供特定的测试场景和检查的严格性。例如:
$ echo "test_add 1 4 5 10 exit_on_fail" >> testData.txt
$ echo "test_divide 100 3 1 33 approximate_compare" >> testData.txt
(像这样进行适当的修改......)
{
// format: testType = function to test. testResponseType = what to do when it fails.
// a, b, c = inputs. expectedResult = comparison.
// example test_add(1, 4, 5) = 1 + 4 + 5 = compared with 10. Strict.
// example test_divide(100, 1, 3) = (100/1)/3 = compared with 33. Approximate, don't fail.
fileHandle >> testType >> a >> b >> c >> expectedResult >> testResponseType;
TestResponseType type = ResponseFromString(testResponseType);
switch (TestTypeFromString(testType))
{
case Test_Add: return Test<type>(a, b, c, expectedResult, Add);
case Test_Divide: return Test<type>(a, b, c, expectedResult, Divide);
default: return false;
}
}
// ...
template <int TestResponseType> //generic test-fn template
bool Test(int a, int b, int c, int result, TestFunctor& fn)
{
}
template <> // specialized for each "reaction" type...
bool Test<Warn>(int a, int b, int c, int result, TestFunctor& fn)
{
return QCOMPARE_WARN(fn(a, b, c) == result);
}
template <>
bool Test<FailOnError>(int a, int b, int c, int result, TestFunctor& fn)
{
QCOMPARE_ASSERT(fn(a, b, c) == result);
return true;
}