GTest源码剖析(二)——TEST宏

C++单元测试实战:从gtest基础到TEST/TEST_F高级应用 单元测试是软件工程中保障代码质量的核心实践,通过隔离验证最小代码单元的逻辑正确性,为重构和持续集成提供安全网。其原理在于模拟各种输入与边界条件,利用断言自动验证预期输出,从而快速定位缺陷。在C++生态中,Google Test(gtest)作为主流框架,通过TEST宏支持独立测试场景,而TEST_F宏结合测试夹具(Fixture)则能优雅管理共享资源与状态隔离。本文聚焦gtest实战,深入解析TEST与TEST_F的设计哲学、断言策略及生命周期管理,并结合测试替身(Mocking)与参数化测试等高级技巧,展 阅读详情

GTest源码剖析——TEST宏

1 TEST宏定义

简单示例:

TEST(Call,makeCall)
{
    ASSERT_TRUE(true);
}

上述代码展开如下:

//step1:声明一个以test_case_name和test_name拼接成的类。 
//      该类包含一个虚函数TestBody(),主要用于执行编写的测试用例需要执行的逻辑;
//      包含一个静态成员变量test_info_,主要用于注册测试用例信息;
//      申明该类不允许copy和assign操作
class Call_makeCall_Test : public ::testing::Test    
{    
public:    
    Call_makeCall_Test();    

private:    
    //虚函数接口,用于执行用例的函数体
    virtual void TestBody();

    //定义 const static 成员变量。
    static ::testing::TestInfo* const test_info_ ; 

    //该类不许copy和assign操作
    Call_makeCall_Test(Call_makeCall_Test const &);
    void operator=(Call_makeCall_Test const &);
}  

//step2:类静态变量赋初值  
::testing::TestInfo* const Call_makeCall_Test::test_info_ =   
    ::testing::internal::MakeAndRegisterTestInfo(  
        "Call",   
        "makeCall",   
        NULL,   
        NULL,   
        ::testing::internal::CodeLocation(__FILE__, __LINE__), 
        ::testing::internal::GetTestTypeId(),
        ::testing::Test::SetUpTestCase,   
        ::testing::Test::TearDownTestCase,   
        new ::testing::internal::TestFactoryImpl<Call_makeCall_Test>);  

//step3:实例化类成员TestBody() 
//函数体实现为用户编写的需要进行测试的代码逻辑 
void Call_makeCall_Test::TestBody()  
{  
    ASSERT(true);  
}  

2 源码解析

2.1 生成测试用例唯一ID: GetTestTypeId()

其中,GetTestTypeId()的目的是为了生成一个唯一的ID,其实现原理非常简单,取类成员静态变量的地址保证唯一性。
该ID用于唯一的标识一个测试用例。

    //定义TypeId为const void*
    typedef const void* TypeId;

    // 定义了一个只包含静态成员变量的模版类TypeIdHelper
        template <typename T>
        class TypeIdHelper 
    {
        public:
            static bool dummy_;
        };

        template <typename T>
        bool TypeIdHelper<T>::dummy_ = false;

    //获取TypeIdHelper类静态变量的地址
        template <typename T>
        TypeId GetTypeId() 
    {
          return &(TypeIdHelper<T>::dummy_);
        }

    //对GetTypeId()进行封装,主要是为了解决跨平台问题
        TypeId GetTestTypeId() 
    {
          return GetTypeId<Test>();
        }

2.2 记录测试用例位置:CodeLocation

记住该测试用例的文件名称和所在行数,该信息为GTEST新加内容,主要用于后期对测试用例信息的快速定位。

struct CodeLocation 
{
  CodeLocation(const std::string& a_file, int a_line)
      : file(a_file), line(a_line) {}

  std::string file;
  int line;
};

2.3 工厂函数:TestFactoryImpl

实现了一个创建TEST类的工厂函数。
从TestFactoryImpl及其父类TestFactoryBase的实现可以看出,其目的仅仅是实现了一个创建TEST类的工厂函数。

template <class TestClass>
class TestFactoryImpl : public TestFactoryBase 
{
public:
  virtual Test* CreateTest() { return new TestClass; }
};
class TestFactoryBase 
{
public:
  virtual ~TestFactoryBase() {}
  virtual Test* CreateTest() = 0;

protected:
  TestFactoryBase() {}

private:
    TestFactoryBase(TestFactoryBase const &);
    void operator=(TestFactoryBase const &);
};

2.4 注册测试用例信息:MakeAndRegisterTestInfo

介绍了前面的几个接口和类,终于到了MakeAndRegisterTestInfo这个函数。
其目的是对测试用例的信息注册到google test中,为后续允许测试用例进行准备。

MakeAndRegisterTestInfo的代码实现如下:
1. new一个TestInfo类;
2. 通过GetUnitTestImpl接口获取一个UnitTestImpl单例;
3. 把TestInfo添加到UnitTestImpl单例中,即对测试用例的信息进行注册。

GTEST_API_ TestInfo* MakeAndRegisterTestInfo(
    const char* test_case_name, 
    const char* name,
    const char* type_param,             //主要用于TEST_P.TEST中其值为NULL
    const char* value_param,            //主要用于TEST_P.TEST中其值为NULL
    CodeLocation code_location,
    TypeId fixture_class_id,
    SetUpTestCaseFunc set_up_tc,        //主要用于TEST_F
    TearDownTestCaseFunc tear_down_tc,  //主要用于TEST_F
    TestFactoryBase* factory)
{
  //new一个TestInfo实例,保存测试用例的相关信息,后续执行是会添加测试结果。
  TestInfo* const test_info = new TestInfo(
          test_case_name, name, type_param, value_param,code_location, fixture_class_id, factory);

  //添加测试用例信息到UnitTestImpl单例中
  GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info);

  return test_info;
}
2.4.1 UnitTestImpl::AddTestInfo()

再来看一下UnitTestImpl类的AddTestInfo()的实现
1. 该接口直接在类中实现,为inline;
2. 对线程安全的死亡测试进行保护;
3. 根据测试用例信息获取一个TestCase类,如果获取不到则创建一个新的TestCase;
4. 把TestInfo添加到TestCase中。

void AddTestInfo(Test::SetUpTestCaseFunc set_up_tc,
                 Test::TearDownTestCaseFunc tear_down_tc,
                 TestInfo* test_info) 
{

  //为了支持线程安全的DeathTest,记住原始工作目录,这里可以先不关心
  if (original_working_dir_.IsEmpty()) 
  {
    original_working_dir_.Set(FilePath::GetCurrentDir());
    GTEST_CHECK_(!original_working_dir_.IsEmpty()) 
      << "Failed to get the current working directory.";
  }

  GetTestCase(test_info->test_case_name(),
              test_info->type_param(),
              set_up_tc,
              tear_down_tc)->AddTestInfo(test_info);
}
2.4.2 UnitTestImpl::GetTestCase()
  • UnitTestImpl的成员变量test_cases_,用于保存所有的test case.
  • UnitTestImpl的成员变量last_death_test_case_,用于标识死亡测试的数量及索引.
  • UnitTestImpl的成员变量test_case_indices_,用于记录测试用例的索引,便于shuffle and restore
TestCase* UnitTestImpl::GetTestCase(const char* test_case_name,
                                    const char* type_param,
                                    Test::SetUpTestCaseFunc set_up_tc,
                                    Test::TearDownTestCaseFunc tear_down_tc) 
{
  //如果能找到该TestCase则直接返回,否则创建一个新的TestCase
  const std::vector<TestCase*>::const_iterator test_case =
      std::find_if(test_cases_.begin(), test_cases_.end(),TestCaseNameIs(test_case_name));

  if (test_case != test_cases_.end())
    return *test_case;

  TestCase* const new_test_case = 
    new TestCase(test_case_name, type_param, set_up_tc, tear_down_tc);

  //如果该TestCase是死亡测试用例,则插入当前最后一个死亡测试用例的后面,否则插入所有测试用例的后面。
  //死亡测试和普通的测试用例均保存在test_cases_中;
  //用last_death_test_case_标识死亡测试用例的位置;
  //该目的是用去如果运行死亡测试用例,保证其能够最先执行。  
  if (internal::UnitTestOptions::MatchesFilter(test_case_name, kDeathTestCaseFilter)) 
  {
    ++last_death_test_case_;
    test_cases_.insert(test_cases_.begin() + last_death_test_case_, new_test_case);
  } 
  else 
  {
    test_cases_.push_back(new_test_case);
  }

  //记录该TestCase的索引,便于shuffle and restore.
  test_case_indices_.push_back(static_cast<int>(test_case_indices_.size()));
  return new_test_case;
}
2.4.3 TestCase::AddTestInfo

该函数实现比较简单.

  • 把TestInfo放入test_info_list_变量中;
  • 添加test_indices_信息
void TestCase::AddTestInfo(TestInfo * test_info) 
{
  test_info_list_.push_back(test_info);
  test_indices_.push_back(static_cast<int>(test_indices_.size()));
}

3 总结TEST宏

至此,已分析完毕TEST宏的源码。

  1. 首先声明一个以test_case_name和test_name拼接成的类。所以需要保证test_case_name和test_name在代码中唯一,避免命名冲突。
  2. 拼接的类中有一个静态成员变量test_info_,该成员变量的唯一作用是利用类静态变量在main之前初始化,对测试用例的信息进行注册。这是GTEST的最精华部分。
  3. 通过MakeAndRegisterTestInfo函数对test_info_进行赋初值的过程,对测试用例的信息进行注册。因为UnitTest和UnitTestImpl均实现为单例,实现了注册测试用例信息到GTest中。
  4. 通过宏定义,实现了TestBody()的逻辑,即我们需要的测试代码,这部分会在运行测试用例时被调用。
  5. TEST宏的主要目的在于提前注册测试用例信息,为后续运行测试用例做准备。

4 参考

github: googletest


ZhaiPillar
2017-09-16

深入gtest源码:从TEST宏到参数化测试的核心机制解析 C++单元测试中,Google Test(gtest)是最受欢迎的测试框架之一。其源码中TEST宏如何将测试函数自动注册为测试用例?ASSERT与EXPECT断言在控制流上有何本质差异?事件监听器如何控制输出并扩展框架行为?参数化测试又是如何通过INSTANTIATE宏实现批量注册的?这些底层机制不仅决定框架的运行效率,也直接影响开发者日常编写测试代码的方式。理解宏展开、静态注册和事件回调的设计思路,能帮助你更高效地使用gtest,并从容应对测试中的疑难杂症。本文以gtest源码为主线,从RUN_ALL_T 阅读详情

相关推荐

深入gtest源码:从断言宏到测试运行的完整机制

在C++工程实践中,单元测试是保障代码质量的基础设施,而GoogleTest(gtest)作为最广泛使用的测试框架,其内部机制常被开发者视为黑盒。理解测试框架的核心原理,不仅有助于编写更可靠的测试用例,还能为二次封装和定制扩展提供支撑。从断言宏的本质出发,EXPECT与ASSERT的实现差异直接决定了测试流程的控制方式;TEST宏的展开过程则揭示了测试类如何注册到全局UnitTest树中。进一步看,RUN_ALL_TESTS的执行路径与TestEventListener监听器架构,使得测试过滤、结果输出和C

weixin_32228501的博客 351

Gtest入门2 Gtest之TEST宏的用法

Googletest宏的用法(整理)1. TestCase的介绍2. TEST宏3. TEST_F宏4. TEST_P宏5. EXPECT_*和ASSERT_*的宏介绍5.1.gtest之断言5.2. gtest断言分类5.2.1 Boolean断言类型5.2.2 二元值断言类型5.2.3 字符串断言类型6. EXPECT_CALL7. 调用测试 1. TestCase的介绍 本章节主要介绍在使用...

sevenjoin的博客 1万+

如何读懂CiteSpace图谱?科研小白必看的节点颜色/年轮/聚类解读手册

本文详细解析CiteSpace图谱的核心视觉元素,包括节点颜色、年轮和聚类标识,帮助科研人员准确解读数据分析结果。通过生物医学案例展示如何从图谱中识别关键文献和研究趋势,提供五步系统解读法和常见错误规避策略,助力科研小白快速掌握文献计量分析技巧。

weixin_29179311的博客 321

最全面的gtest的TEST宏源码解析及自动调度机制

GTEST的TEST原理分析及自动调度解析 介绍 Gtest是google开发的一个开源的C++测试框架,可在Linux, Windows,Mac多个平台上对C++源码进行测试,它提供了丰富的断言、致命和非致命判断、参数化、”死亡测试”等等。 使用gtest时,就是编写断言(assertions),断言语句会检测条件是否为真。一个断言可存在三种结果:success(成功),nonfatal failure(非致命失败),或 fatal failure(致命失败)。当出现致命失败时,终止当前函数;否则程序继续

Jayse的博客 3070

Matlab实战:从零搭建弹道导弹六自由度仿真模型(附完整代码)

本文详细介绍了如何使用Matlab从零搭建弹道导弹六自由度仿真模型,涵盖仿真环境配置、核心运动方程实现、气动力建模及仿真结果分析。通过完整代码示例,帮助读者掌握弹道导弹六自由度仿真的关键技术,适用于航空航天工程和复杂系统建模领域。

x8y9z0的博客 949

Python实战:5分钟搞定固定翼无人机三自由度仿真(附完整代码)

本文提供了一个基于Python的固定翼无人机三自由度仿真快速实现方案。通过面向对象设计,封装了核心运动学模型,并对比了欧拉法与龙格-库塔法两种积分方法。文章附有完整实例代码,帮助算法工程师和研究人员在5分钟内搭建轻量级仿真环境,用于快速验证控制律、路径规划等核心算法逻辑。

docker7nomad的博客 752

gtest使用简介

TEST需要两个参数:第一个是test suite的名字,test suite代表一组相关的测试脚本,比如如上的三个Test的test suite的名字都是FactorialTest,都是针对于函数Factorial的测试;这样做的目的是为了能将测试用例分成不同的层次,当在开发过程中,你只希望针对一些特殊的用例进行测试的时候,可以通过 --gtest_filter 来选择只运行指定的用例。但在一些环境下,也是一种有效的实现方式。如上的测试用例中,考虑到负数,一些特殊的数(0,1,2,3)以奇偶数的判断。

junguo的专栏 6274

23数字图像置乱技术(matlab程序)

所谓“置乱”,就是将图像的信息次序打乱,a像素移动到b像素位置上,b像素移动到c像素位置上,……,使其变换成杂乱无章难以辨认的图片。数字图像置乱技术属于加密技术,是指发送发借助数学或者其他领域的技术,对一幅有意义的数字图像做变换,使之变成一幅杂乱无章的图像用于传输。在图像传输过程中,它通过对图像像素矩阵的重排,破坏了图像矩阵的相关性,使非法截获者无法从杂乱无章的图像中获得原图像信息,以此实现信息的加密。接收方经去乱解密可恢复原图像。

m0_57943157的博客 1212

GTest源码剖析(四)——TEST_P宏

GTest源码剖析——TEST_P宏GTest源码剖析TEST_P宏 TEST_P宏用法 TestWithParam 类 1 TestWithParam 类定义 2 WithParamInterface 模版类定义 INSTANTIATE_TEST_CASE_P宏 1 INSTANTIATE_TEST_CASE_P宏展开 2 参数生成器 21 参数生成器Values 22 ParamGenerato

Pillary的专栏 1万+

ubuntu20.04安装Qt5.15.2并配置环境

qt官方取消了离线安装的方式,所以推荐在线安装,当然,如果想要自己通过源码编译也可以,参考官方文档:https://wiki.qt.io/Building_Qt_5_from_Git。 在线安装: 1.到官方网站下载:wget https://download.qt.io/official_releases/online_installers/qt-unified-linux-x64-online.run 2.修改文件权限:chmod 777 qt-unified-linux-x64-online.run

f120854632的博客 8809

手把手教你模拟登录豆瓣并爬取个人书影音数据:从Cookie解析到反爬攻防实战

在开始写代码之前,先明确我们需要的工具。:建议用3.10以上版本,方便使用一些新特性(如match语句)httpx:比requests更现代,支持HTTP/2,异步性能强,连接池复用好:解析HTML,语法简单,容错性强selenium:仅用于处理登录时的滑块验证(模拟真人)pandas:最终数据清洗和导出Excel/CSVretrying:自动重试机制,应对临时封禁:随机UA,降低特征lxml:作为BeautifulSoup的解析器,速度快为什么不只用requests?

2201_76125261的博客 581

【单元测试】C++单元测试框架Google Test入门之七:深入解析GTEST

深入解析”对我来说的确有些难度,所以我尽量将我学习到和观察到的gtest内部实现介绍给大家。本文算是抛砖引玉吧,只能是对gtest的整体结构的一些介绍,想要了解更多细节最好的办法还是看gtest源码,如果你看过gtest源码,你会发现里面的注释非常的详细!好了,下面就开始了解gtest吧。::同时也看看TEST_F宏::GetTypeId\ public :\ };

Friday 1355

2026年北京君正数字IC笔试试卷带答案

本文摘要:该文档是一份数字IC设计相关的考试试题,包含单选题、多选题、波形分析题和代码设计题。内容涵盖时序约束、半导体工艺、状态机设计、逻辑综合、异步FIFO设计等知识点。试题解析详细,重点考察数字电路基础、时序分析和Verilog代码实现能力。典型题目包括多周期路径设置、Moore/Mealy状态机区别、同步复位与异步复位特性、RISC-V架构特点等,并提供了异步FIFO的Verilog实现参考代码。(149字)

Open 118

GTest源码剖析(三)——TEST_F宏

GTest源码剖析——TEST_F宏GTest源码剖析TEST_F宏 TEST_F宏与TEST宏的区别 1 TEST_F宏定义 2 TEST宏定义 3 对比分析 31 拼接类对比 32 调用MakeAndRegisterTestInfo传参对比 TEST_F宏作用 1 TestCase级扩展 2 Test级扩展 参考 1 TEST_F宏与TEST宏的区别TEST_F宏和TEST宏的实现非常接近,只是

Pillary的专栏 6540

K230+canMV开发中常见的数据类型转换参考示例

【代码】K230+canMV开发中常见的数据类型转换参考示例。

weixin_47446386的博客 70

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

【C++ 单元测试】 GTest 指南:剖析 TEST_P 与 TYPED_TEST

在日常开发中,Google Test(GTest)已经成为C++单元测试领域的事实标准。从最初的 `TEST` 与 `TEST_F` 出发,很多团队逐渐发现针对不同类型或不同输入参数进行大规模测试时,往往需要更灵活的方式来组织测试用例,这就是 `TEST_P` 和 `TYPED_TEST` 的诞生背景。毕竟,正如荣格所言,“理解越多,也就越能够包容”,对测试框架的深入了解也能帮助我们更好地构建健壮的代码。

探索C++编程的奥秘,分享深入的技术见解和实践,旨在激发读者创造力与解决问题的思维。 1730

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

Gtest源码解析 - GoogleTest(八)

一、前言 “深入解析”对我来说的确有些难度,所以我尽量将我学习到和观察到的gtest内部实现介绍给大家。本文算是抛砖引玉吧,只能是对gtest的整体结构的一些介绍,想要了解更多细节最好的办法还是看gtest源码,如果你看过gtest源码,你会发现里面的注释非常的详细!好了,下面就开始了解gtest吧。 二、从TEST宏开始 前面的文章已经介绍过TEST宏的用法了,通过TEST宏,我们可以非法简单、方便的编写测试案例,比如: TEST(FooTest,Demo) { EXPECT_EQ(1,...

生活需要深度 2241

计算机控制技术及应用

《计算机控制技术及应用》通过总结作者的科研成果和吸收国内外的先进理论、方法和技术,以计算机控制系统的网络化、开放化、智能化和集成化发展趋势为主线索,主要介绍计算机控制系统的基本概念和计算机控制系统的典型形式,计算机控制系统的数学描述与基本分析方法,以及数字PID控制器、最少拍控制系统、达林算法、状态变量设计法等设计方法及其各种改进算法。重点突出计算机控制系统输入输出通道接口的设计方法和典型控制系统的设计案例与实现方法等。

GTest源码剖析(一)——概述

GTest源码剖析——概述GTest源码剖析概述 概述 GTest使用 1 main函数 2 TEST宏的使用 3 TEST_F宏的使用 4 TEST_P宏的使用 参考 1 概述Source: https://github.com/google/googletest Build: g++ -isystem ${GTEST_DIR}/include -I${GTEST_DIR} -pthread -

Pillary的专栏 1839

(转)玩转Google开源C++单元测试框架Google Test系列(gtest)之七 - 深入解析gtest

原文链接:http://www.cnblogs.com/coderzh/archive/2009/04/11/1433744.html 一、前言 “深入解析”对我来说的确有些难度,所以我尽量将我学习到和观察到的gtest内部实现介绍给大家。本文算是抛砖引玉吧,只能是对gtest的整体结构的一些介绍,想要了解更多细节最好的办法还是看gtest源码,如果你看过gtest源码...

dengshen7813的博客 165

GTest源码剖析(七)——断言

GTest源码剖析——断言GTest源码剖析断言 ASSERT_TRUE宏 1 ASSERT_TRUE宏 和 EXPECT_TRUE宏 的区别 11 GTEST_MESSAGE_宏 12 AssertHelper类 2 ASSERT_TRUE宏的实现 21 AssertionResult类 1 ASSERT_TRUE宏ASSERT_TRUE宏和ASSERT_FALSE宏几乎认为无区别,仅仅是参数取反

Pillary的专栏 1492

GTest源码剖析(五)——传入参数分析及InitGoogleTest

GTest源码剖析——传入参数分析及InitGoogleTestGTest源码剖析传入参数分析及InitGoogleTest InitGoogleTest源码分析 1 InitGoogleTestImpl 2 ParseGoogleTestFlagsOnly 3 UnitTestImplPostFlagParsingInit 4 UnitTestImplConfigureXmlOutput 传入参数

Pillary的专栏 8542

Google Test(GTest)使用方法和源码解析——自动调度机制分析

在《Google Test(GTest)使用方法和源码解析——概况》一文中,我们简单介绍了下GTest的使用和特性。从这篇博文开始,我们将深入代码,研究这些特性的实现。(转载请指明出于breaksoftware的csdn博客) 测试用例的自动保存 当使用一组宏构成测试代码后,我们并没有发现调用它们的地方。GTest框架实际上是通过这些宏,将我们的逻辑保存到类中,...

方亮的专栏 9495

Google Test(GTest)使用方法和源码解析——结果统计机制分析

        在分析源码之前,我们先看一个例子。以《Google Test(GTest)使用方法和源码解析——概况 》一文中最后一个实例代码为基准,修改最后一个“局部测试”结果为错误。(转载请指明出于breaksoftware的csdn博客) class ListTest : public testing::Test { protected: virtual void SetUp() ...

方亮的专栏 6779

gperftools 中的 GoogleTest:从 CMake 构建、FetchContent 集成到控制宏定制的完整指南

本文以 GoogleTest 官方构建文档(vendored 于 [vendor/googletest/googletest/README.md](https://link.gitcode.com/i/f90f8910052f1c32e3189f4b4c5023ed))为核心,系统讲解在任意 C++ 项目中如何编译、安装、集成 GoogleTest 测试框架,并深入剖析其关键的编译期控制宏(`GT

gitblog_00499的博客 443

Gtest源码剖析:1.实现一个超级简单的测试框架xtest

下面的代码模仿gtest实现,主要说明了以下两点: ASSERT_* 和 EXPECT_*系列断言的原理和作用. gtest是怎样通过宏自动注册测试代码让其自动运行的. 1 #include &lt;iostream&gt; 2 #include &lt;string&gt; 3 #include &lt;memory&gt; 4 #include &lt;vector&gt; ...

dolphin98629的专栏 754

GTest源码剖析(六)——RUN_ALL_TESTS

GTest源码剖析——RUN_ALL_TESTSGTest源码剖析RUN_ALL_TESTS RUN_ALL_TESTS源码分析 1 UnitTestRun 2 HandleExceptionsInMethodIfSupported 3 UnitTestImplRunAllTests 5 TestCaseRun 6 TestCaseRun 7 TestRun 参考 1 RUN_ALL_TESTS()

Pillary的专栏 6673
上一篇: GTest源码剖析(一)——概述
下一篇: GTest源码剖析(三)——TEST_F宏
沐寒握冰
博客等级 码龄14年 57粉丝 58原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值