nlib
testing/failure/failure.cpp
FailureDemoというテストグループが定義されています。 名前のとおり殆どのテストが失敗するようにできています。
テストに失敗したときに分かり易いメッセージを表示する方法について、コードを交えて説明されています。
// define NLIB_USE_GTEST to use googletest
// #define NLIB_USE_GTEST
TEST(FailureDemo, UseOperatorLtDemo) {
int myArray[100];
for (int i = 0; i < 100; ++i) myArray[i] = i * 2;
myArray[50] = 500; // set bad data
for (int i = 0; i < 100; ++i) {
// you can use operator<< to print the messages if the test fails
ASSERT_EQ(i * 2, myArray[i]) << "i = " << i << ", myArray[" << i << "] is wrong.";
}
}
struct MyStruct {
float x;
float y;
float z;
public:
bool operator==(const MyStruct& rhs) const { return x == rhs.x && y == rhs.y && z == rhs.z; }
};
NLIB_TESTING_OSTREAM& operator<<(NLIB_TESTING_OSTREAM& str, const MyStruct& data) {
// you can also define function PrintTo().
// void PrintTo(const MyStruct& data, NLIB_TESTING_OSTREAM* str)
// PrintTo() has priority over operator<<().
// you can compile this function with gtest,
// because NLIB_TESTING_OSTREAM becomes ::std::ostream if gtest is used.
str << "{ x = " << data.x << ", y = " << data.y << ", z = " << data.z << " }";
return str;
}
TEST(FailureDemo, DefineOperatorLtDemo) {
MyStruct vec1 = {1.f, 2.f, 3.f};
MyStruct vec2 = {2.f, 3.f, 4.f};
// overloaded operator<<() is called
ASSERT_EQ(vec1, vec2);
}
TEST(FailureDemo, FloatingPointError1) {
double p = 0.1;
double q = 0.2;
// p + q is not equal to 0.3 exactly.
EXPECT_EQ(0.3, p + q);
}
TEST(FailureDemo, FloatingPointError2) {
double p = 0.1;
double q = 0.2;
// you should use EXPECT_DOUBLE_EQ or EXPECT_FLOAT_EQ for floating point numbers.
EXPECT_DOUBLE_EQ(0.3, p + q);
}
static void Subroutine(int i) { ASSERT_LT(i, 100); }
TEST(FailureDemo, FailureInSubroutine1) {
for (int i = 0; i <= 100; ++i) {
// using SCOPED_TRACE(),
// you can construct the message for tracing failures in subroutines.
// you can use operator<<() to construct the message.
// The message is printed when some tests fail in this scope.
SCOPED_TRACE(::testing::Message() << "FailureInSubroutine1(idx = " << i << ")");
Subroutine(i);
}
}
TEST(FailureDemo, FailureInSubroutine2) {
for (int i = 0; i < 100; ++i) {
// you can also put a string directly as an argument for SCOPED_TRACE().
SCOPED_TRACE("FailureInSubroutine2");
Subroutine(i);
}
}
NLIB_PATHMAPPER_FORSAMPLE
bool SampleMain(int argc, char** argv) {
InitPathMapperForSample();
char path[512];
char buf[512];
size_t count;
g_PathMapper.ResolvePath(&count, path, "nlibpath:///readwrite/failure.xml");
nlib_snprintf(&count, buf, "xml:%s", path);
::testing::GTEST_FLAG(output) = buf;
// RUN_ALL_TESTS returns 0 if all the tests are successful.
// You can use the return value of main() function.
return RUN_ALL_TESTS() != 0;
}
NLIB_MAINFUNC