UnitTest++ Why are CheckEqual() overloads that take non const char* needed
在UnitTest ++框架中,Checks.cpp模块中有4个重载版本的CheckEqual。 每个重载都对预期或实际采用不同的常量。 然后所有四个只调用CheckStringsEqual(),它将char const *作为预期和实际的。 我可以删除重载并且所有内容编译都很好但是当使用数组语法声明字符串时,单元测试在传递除两个const字符串以外的任何内容时失败,即
1 | char txt1[]="Hello"; |
澄清
原始的UnitTest ++代码展示了这种行为,而不仅仅是我的实现。 此外,当我删除过载导致我受阻时,测试失败了。
四个重载是:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | void CheckEqual(TestResults& results, char const* expected, char const* actual, TestDetails const& details, std::string const& msg) //msg defaults to ="" in .h { CheckStringsEqual(results, expected, actual, details, msg); } void CheckEqual(TestResults& results, char* expected, char* actual, TestDetails const& details) { CheckStringsEqual(results, expected, actual, details); } void CheckEqual(TestResults& results, char* expected, char const* actual, TestDetails const& details) { CheckStringsEqual(results, expected, actual, details); } void CheckEqual(TestResults& results, char const* expected, char* actual, TestDetails const& details) { CheckStringsEqual(results, expected, actual, details); } |
CheckStringsEqual是
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | void CheckStringsEqual(TestResults& results, char const* expected, char const* actual, TestDetails const& details, std::string const& msg="") { using namespace std; if (strcmp(expected, actual)) { UnitTest::MemoryOutStream stream; stream << msg; stream <<" Expected" << expected <<" but was" << actual; results.OnTestFailure(details, stream.GetText()); } } |
最后,这里有一些测试,如果你注释掉除了第一个CheckEqual之外的所有测试,它们中的一些会失败
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | char txt1[] ="Hello"; // non-const on purpose so no folding of duplicate data char txt2[] ="Hello"; TEST(CheckEqualsWithStringsWorksOnContentsNonConstNonConst) { char const* const p1 = txt1; char const* const p2 = txt2; TestResults results; CheckEqual(results, p1, p2, TestDetails("","","", 0)); CHECK_EQUAL(0, results.GetFailureCount()); } TEST(CheckEqualsWithStringsWorksOnContentsConstConst) { char* const p1 = txt1; char* const p2 = txt2; TestResults results; CheckEqual(results, p1, p2, TestDetails("","","", 0)); CHECK_EQUAL(0, results.GetFailureCount()); } TEST(CheckEqualsWithStringsWorksOnContentsNonConstConst) { char* const p1 = txt1; char const* const p2 = txt2; TestResults results; CheckEqual(results, p1, p2, TestDetails("","","", 0)); CHECK_EQUAL(0, results.GetFailureCount()); } TEST(CheckEqualsWithStringsWorksOnContentsConstNonConst) { char const* const p1 = txt1; char* const p2 = txt2; TestResults results; CheckEqual(results, p1, p2, TestDetails("","","", 0)); CHECK_EQUAL(0, results.GetFailureCount()); } |
第一个
使用相同数量的参数,我不确定为什么它们会以这种方式