Google单元测试sample分析(四)

这篇具有很好参考价值的文章主要介绍了Google单元测试sample分析(四)。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

GoogleTest单元测试可用实现在每个测试用例结束后监控其内存使用情况,

可以通过GoogleTest提供的事件侦听器EmptyTestEventListener 来实现,下面通过官方提供的sample例子,路径在samples文件夹下的sample10_unittest.cpp

// Copyright 2009 Google Inc. All Rights Reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


// This sample shows how to use Google Test listener API to implement
// a primitive leak checker.

#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 {
// We will track memory used by this class.
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;

// This event listener monitors how many Water objects are created and
// destroyed by each test, and reports a failure if a test leaks some Water
// objects. It does this by comparing the number of live Water objects at
// the beginning of a test and at the end of a test.
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_;
};

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);
}
}  // namespace

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 we are given the --check_for_leaks command line flag, installs the
  // leak checker.
  if (check_for_leaks) {
    TestEventListeners& listeners = UnitTest::GetInstance()->listeners();

    // Adds the leak checker to the end of the test event listener list,
    // after the default text output printer and the default XML report
    // generator.
    //
    // The order is important - it ensures that failures generated in the
    // leak checker's OnTestEnd() method are processed by the text and XML
    // printers *before* their OnTestEnd() methods are called, such that
    // they are attributed to the right test. Remember that a listener
    // receives an OnXyzStart event *after* listeners preceding it in the
    // list received that event, and receives an OnXyzEnd event *before*
    // listeners preceding it.
    //
    // We don't need to worry about deleting the new listener later, as
    // Google Test will do it.
    listeners.Append(new LeakChecker);
  }
  return RUN_ALL_TESTS();
}

通过Water类来重写new和delete方法来实现记录内存分配/释放的情况,另外通过LeakChecker 继承自EmptyTestEventListener 并实现OnTestStart(测试用例开始前运行)和OnTestEnd方法(测试用例结束后运行)

关于LeakChecker的使用是先获取系统提供的listeners ,然后把自定义事件加入到系统中去即可。
TestEventListeners& listeners = UnitTest::GetInstance()->listeners();
listeners.Append(new LeakChecker);文章来源地址https://www.toymoban.com/news/detail-735033.html

到了这里,关于Google单元测试sample分析(四)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • elasticsearch-7.13.3 升级log4j 到log4j-2.17.1

    1、升级原因 log4j低版本存在严重漏洞,根据需要升级到安全版本,不一定是最新。 log4j-2.17.1 jar包下载地址https://archive.apache.org/dist/logging/log4j/2.17.1/ 2、下载后解压apache-log4j-2.17.1-bin.tar.gz 升级需要用到截图中四个jar包 3、升级 删除旧版本log4j 进入elasticsearch-7.13.3目录 $ rm -rf l

    2024年02月12日
    浏览(54)
  • Log4J

    为什么要用日志? -- 方便调试代码 什么时候用?什么时候不用? ​ 出错调试代码时候用 生产环境下就不需要,就需要删除 怎么用? -- 输出语句 ​ log4j是Apache的一个开放源代码的项目,通过使用log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件、甚至是套接口服

    2024年02月08日
    浏览(43)
  • Log4j源码解析

    Log4j源码解析 主要流程 Logger logger = Logger.getLogger(Main.class); 1、通过Logger.getLogger(Class clazz) 或 Logger.getLogger(String name)进入。 2、加载LogManager进jvm, 执行静态代码块执行初始化, 创建出RepositorySelector实例及LoggerRepository实例(Hierarchy)。 3、调用OptionConverter.selectAndConfigure(URL url, String

    2024年02月15日
    浏览(49)
  • log4j漏洞详解

    log4j全名就是(log for java),就是apache的一个开源的日志记录组件 ,它在Java项目中使用的比较广泛。 使用方法:                 1.pom引入依赖                 2.获取logger实例                 3.logger.info() debug() error() warn()... 优点:功能丰富,易于集成

    2024年02月16日
    浏览(44)
  • 【日志加载 log4j】

    2.编写配置 3.获取日志对象 4.1 Loggers 记录器 4.2 Appenders 输出源 4.3 Layouts 布局 5. 配置文件 log4j.properties

    2024年02月11日
    浏览(91)
  • log4j警告之log4j:WARN No appenders could be found for logger

    目录 1. 警告信息  2. 错误解读  3.解决办法   错误输出信息: log4j:WARN No appenders could be found for logger (org.apache.flink.api.java.utils.PlanGenerator). log4j:WARN Please initialize the log4j system properly. log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info. 如果找不到默认配置文件log4j

    2024年02月14日
    浏览(56)
  • Log4j远程代码执行漏洞

    简介 漏洞描述 Apache Log4j 是 Apache 的一个开源项目,Apache log4j-2 是 Log4j 的升级,我们可以控制日志信息输送的目的地为控制台、文件、GUI组件等,通过定义每一条日志信息的级别,能够更加细致地控制日志的生成过程。 Log4j-2中存在JNDI注入漏洞,当程序将用户输入的数据日志

    2024年02月11日
    浏览(68)
  • log4j JNDI注入漏洞

    目录 log4j JNDI注入漏洞 一、LDAP介绍 二、JDBC介绍 三、JNDI介绍 四、JNDI命名引用 五、log4j JNDI注入漏洞 ​LDAP是一种协议,LDAP 的全称是 Lightweight Directory Access Protocol,轻量目录访问协议。 ​JDBC是一种规范,JDBC的全称是Java数据库连接(Java Database connect),它是一套用于执行SQL语句

    2024年02月01日
    浏览(46)
  • log4j日志框架的使用

    log4j的配置文件可以理解成有2部分 1根日志记录器  2 各appender(输出源)配置 入口 loggerManager的静态代码块 在loggerManager的静态代码块中,完成对配置文件的读取和解析 然后组装成框架的Logger对象、appender对象完成初始化操作 当调用logger.info打印日志时,和logback的流程基本一样

    2024年02月04日
    浏览(61)
  • 用Log4j 2记录日志

    下面代码示例的maven工程中的pom.xml文件中需要增加对Log4j 2的依赖: 配置说明参考文档 https://logging.apache.org/log4j/2.x/manual/configuration.html 配置文件中pattern的详细说明 例如,下面配置文件片段中用到了pattern: pattern的详细说明请参考: https://logging.apache.org/log4j/2.x/manual/layouts.ht

    2024年02月14日
    浏览(97)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包