在每个“基于文件的集成”测试结束时,我想清除相关文件的临时文件夹。
如果测试失败,我想留下这些文件,以便可以查看意外的输出。
在Google Test的TearDown中有没有一种方法来检查测试是否失败?
在每个“基于文件的集成”测试结束时,我想清除相关文件的临时文件夹。
如果测试失败,我想留下这些文件,以便可以查看意外的输出。
在Google Test的TearDown中有没有一种方法来检查测试是否失败?
在 Google Test 的 TearDown() 函数中,有没有办法检查测试是否失败?
是的,您可以通过查询::testing::Test::HasFailure()
来实现在夹具的测试用例中计数器成员的故障情况并将结果用于在夹具的TearDown()
函数中查询。下面是一个简单的示例:
#include <gtest/gtest.h>
#include <iostream>
struct Fixture : public ::testing::Test {
virtual void SetUp() {
fails = 0;
}
virtual void TearDown() {
if (fails > 0) {
std::cerr << "Fixture::TearDown sees failures" << std::endl;
}
}
unsigned fails;
};
TEST_F(Fixture, foo) {
EXPECT_EQ(1,0);
fails += ::testing::Test::HasFailure();
}
TEST_F(Fixture, bar) {
EXPECT_EQ(1,1);
fails += ::testing::Test::HasFailure();
}
int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
然后输出:
[==========] Running 2 tests from 1 test case.
[----------] Global test environment set-up.
[----------] 2 tests from Fixture
[ RUN ] Fixture.foo
/home/imk/dev/so/gtest/main.cpp:19: Failure
Expected: 1
To be equal to: 0
Fixture::TearDown sees failures
[ FAILED ] Fixture.foo (0 sec)
[ RUN ] Fixture.bar
[ OK ] Fixture.bar (0 sec)
[----------] 2 tests from Fixture (0.001 sec total)
[----------] Global test environment tear-down
[==========] 2 tests from 1 test case ran. (1 ms total)
[ PASSED ] 1 test.
[ FAILED ] 1 test, listed below:
[ FAILED ] Fixture.foo
1 FAILED TEST
TearDown()
中检查 ::testing::Test::HasFailure()
。 - Mujtaba AldebesHasFailure()
返回布尔值,所以它将始终计算为1)。#include <gtest/gtest.h>
#include <iostream>
struct Fixture : public ::testing::Test {
virtual void SetUp() {}
virtual void TearDown() {
if (::testing::Test::HasFailure()) {
std::cerr << "Fixture::TearDown sees failures" << std::endl;
} else {
std::cout << "Fixture::TearDown sees NO failures" << std::endl;
}
}
};
TEST_F(Fixture, foo) { EXPECT_EQ(0, 0); }
TEST_F(Fixture, bar) { EXPECT_EQ(1, 0); }
TEST_F(Fixture, car) { EXPECT_EQ(2, 2); }
TEST_F(Fixture, tar) { EXPECT_EQ(3, 0); }