几年前,我为“模拟”对象编写了一些简单的库。我的目标是检查与函数调用相关的所有内容。在测试中我写了这样的东西:
MyMockedObject my;
mock::expect(my, "foo").in(10).out(20).returns(30);
mock::expect(my, "bar").throws(logic_error("bar failed"));
int v;
// test that my::baz() invokes my.foo(10, v)
// then my.bar which fails with the exception
my.baz();
你的任务似乎更容易一些。您所需要的只是一种描述您的期望的方法,以及测试运行器中的一些技巧,以在测试结束时验证它们(根据输入)。您的期望是例外,只需以某种方式构建它们并与输入相关联。在您的示例中,您完成了一半的工作。
typedef std::map<Input, Exception> Expectations;
typedef std::pair<Input, Exception> Expectation;
// somewhere before the tests
expectations.insert(make_pair(Input(5)), NoThrowAnything);
expectations.insert(make_pair(Input(0)), MyException("some message"));
expectations.insert(make_pair(Input(-1)), MyOtherException("another message"));
void run_test(const Expectation& expect)
{
try {
// run the real test here based on Input (expect.first)
check_expectation(expect);
} catch (const Exception& ex) {
check_expectation(expect, ex);
}
}
void run_all_tests(const Expectations& expects)
{
for (e : expects) {
try {
run_test(e);
} catch (const ExpectationException ex) {
// failed expectation
}
}
}
void check_expectation(const Expectation& expect)
{
if (expect.second != NoThrowAnything) {
throw ExpectationFailure(expect);
}
}
void check_expectation(const Expectation& expect, const Exception& ex)
{
if (expect.second != ex) {
throw ExpectationMismatch(expect, ex);
}
}