1.简介
示例#10展示了如何使用侦听器API来实现基本内存泄漏检查。
2.用法
#include <stdio.h>
#include <stdlib.h>
#include "gtest/gtest.h"
using ::testing::EmptyTestEventListener;
using ::testing::InitGoogleTest;
using ::testing::Test;
using ::testing::TestEventListeners;
using ::testing::TestInfo;
using ::testing::TestPartResult;
using ::testing::UnitTest;
namespace {
class Water {
public:
void* operator new(size_t allocation_size) {
allocated_++;
return malloc(allocation_size);
}
void operator delete(void* block, size_t ) {
allocated_--;
free(block);
}
static int allocated() { return allocated_; }
private:
static int allocated_;
};
int Water::allocated_ = 0;
class LeakChecker : public EmptyTestEventListener {
private:
void OnTestStart(const TestInfo& ) override {
initially_allocated_ = Water::allocated();
}
void OnTestEnd(const TestInfo& ) override {
int difference = Water::allocated() - initially_allocated_;
EXPECT_LE(difference, 0) << "Leaked " << difference << " unit(s) of Water!";
}
int initially_allocated_;
};
TEST(ListenersTest, DoesNotLeak) {
Water* water = new Water;
delete water;
}
TEST(ListenersTest, LeaksWater) {
Water* water = new Water;
EXPECT_TRUE(water != nullptr);
}
}
int main(int argc, char** argv) {
InitGoogleTest(&argc, argv);
bool check_for_leaks = false;
if (argc > 1 && strcmp(argv[1], "--check_for_leaks") == 0)
check_for_leaks = true;
else
printf("%s\n",
"Run this program with --check_for_leaks to enable "
"custom leak checking in the tests.");
if (check_for_leaks) {
TestEventListeners& listeners = UnitTest::GetInstance()->listeners();
listeners.Append(new LeakChecker);
}
return RUN_ALL_TESTS();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)