zoukankan      html  css  js  c++  java
  • Google单元测试框架gtest之官方sample笔记4--事件监控之内存泄漏测试

    sample 10 使用event listener监控Water类的创建和销毁。在Water类中,有一个静态变量allocated创建一次值加一,销毁一次值减一为了实现这个功能,重载了new和delete关键字,然后在new和delete函数中,做allocated的增减和记录allocated变量的值。

    class Water {
     public:
      // Normal Water declarations go here.
    // operator new and operator delete help us control water allocation.
      void* operator new(size_t allocation_size) {
        allocated_++;
        return malloc(allocation_size);
      }
    ​
      void operator delete(void* block, size_t /* allocation_size */) {
        allocated_--;
        free(block);
      }
    ​
      static int allocated() { return allocated_; }
    ​
     private:
      static int allocated_;
    };
    ​
    int Water::allocated_ = 0;

    gtest的event listener能在TEST执行前和执行后调用,然后就可以判断TEST执行完后是否发生泄漏。event listner是非入侵式检测,不需要在TEST里写测试代码,而是在TEST之外执行特定的监控代码。

    注册event监听的方法如下,在每个测试前执行OnTestStart,在测试后执行OnTestEnd。计算int difference = Water::allocated() - initially_allocated_;就可以得知是否发生内存泄漏,忘记了删除new的对象。

    class LeakChecker : public EmptyTestEventListener {
     private:
      // Called before a test starts.
      void OnTestStart(const TestInfo&  test_info ) override {
        initially_allocated_ = Water::allocated();
      }
    ​
      // Called after a test ends.
      void OnTestEnd(const TestInfo& /* test_info */) override {
        int difference = Water::allocated() - initially_allocated_;
    ​
        // You can generate a failure in any event handler except
        // OnTestPartResult. Just use an appropriate Google Test assertion to do
        // it.
        EXPECT_LE(difference, 0) << "Leaked " << difference << " unit(s) of Water!";
      }
    ​
      int initially_allocated_;
    };
    ​
    // 如果检查泄漏,则注册event listener监控
    if (check_for_leaks) {
        TestEventListeners& listeners = UnitTest::GetInstance()->listeners();
        listeners.Append(new LeakChecker);
    }

    测试代码如下,由于使用的是非入侵式检测,所以TEST函数和普通的测试一样。下面的DoesNotLeak测试无内存泄漏发生,而LeaksWater测试,会发生内存泄漏。

    TEST(ListenersTest, DoesNotLeak) {
      Water* water = new Water;
      delete water;
    }
    ​
    // This should fail when the --check_for_leaks command line flag is specified.
    TEST(ListenersTest, LeaksWater) {
      Water* water = new Water;
      EXPECT_TRUE(water != nullptr);
    }

    不启用内存泄漏测试时的输出结果:

    使用内存泄漏测试时的输出结果:

     

    尊重技术文章,转载请注明!

    Google单元测试框架gtest之官方sample笔记4--事件监控之内存泄漏测试

    https://www.cnblogs.com/pingwen/p/14482187.html

  • 相关阅读:
    zbb20170802 Windows平台使用Gitblit搭建Git服务器图文教程
    zbb20170728 oracle 查看被锁对象
    zbb20170726 Spring Controller 获取请求参数的几种方法
    zbb20170726 spring访问静态文件访问
    zbb20170720 extjs 类似桌面的页面布局
    zbb20170718 Eclipse 导入外部项目无法识别为web项目并且无法在部署到tomcat下
    zbb20170717Spring4 MVC Hibernate4集成 Annotation maven 各种版本
    zbb20170630 web项目发布至tomcat的ROOT下方法(开发环境和部署环境)
    3.语句的增删改查
    1、java面试
  • 原文地址:https://www.cnblogs.com/pingwen/p/14482187.html
Copyright © 2011-2022 走看看