c – 如何为第三方遗留代码创建测试对象
发布时间:2020-12-16 07:24:51 所属栏目:百科 来源:网络整理
导读:我有一个代码库,我实现的许多类派生自我公司其他部门提供的类.使用这些其他设备通常具有工作关系,就好像它们是第三方中间件供应商一样. 我正在尝试编写测试代码而不修改这些基类.但是,创建有意义的测试存在问题 由于缺少接口而导致的对象: //ACommonClass.h
我有一个代码库,我实现的许多类派生自我公司其他部门提供的类.使用这些其他设备通常具有工作关系,就好像它们是第三方中间件供应商一样.
我正在尝试编写测试代码而不修改这些基类.但是,创建有意义的测试存在问题 //ACommonClass.h #include "globalthermonuclearwar.h" //which contains deep #include dependencies... #include "tictactoe.h" //...and need to exist at compile time to get into test... class Something //which may or may not inherit from another class similar to this... { public: virtual void fxn1(void); //which often calls into many other classes,similar to this //... int data1; //will be the only thing I can test against,but is often meaningless without fxn1 implemented //... }; 我通常会提取一个界面并从那里开始工作,但由于这些是“第三方”,我无法提交这些更改. 目前,我已经创建了一个单独的文件,该文件包含在需要知道的基础上在第三方提供的基类头中定义的函数的伪实现,如“使用传统代码”一书中所述. 我的计划是继续使用这些定义,并为我需要的每个第三方类提供替代测试实现: //SomethingRequiredImplementations.cpp #include "ACommonClass.h" void CGlobalThermoNuclearWar::Simulate(void) {}; // fake this and all other required functions... // fake implementations for otherwise undefined functions in globalthermonuclearwar.h's #include files... void Something::fxn1(void) { data1 = blah(); } //test specific functionality. 但在我开始这样做之前,我想知道是否有人尝试在类似于我的代码库上提供实际对象,这将允许创建新的测试特定类来代替实际的第三方类. 请注意,所有相关的代码库都是用C语言编写的. 解决方法
Mock objects适合这种任务.它们允许您模拟其他组件的存在而无需它们存在.您只需在测试中定义预期的输入和输出.
Google有一个很好的C模拟框架. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |