简体   繁体   English

C ++中的单元测试和模拟小型,类似值的类

[英]Unit testing and mocking small, value-like classes in C++

I am trying to set up some unit tests for an existing c++ project. 我正在尝试为现有的c ++项目设置一些单元测试。

Here's the setup: I have chosen Google Mock, which includes Google Test. 设置如下:我选择了Google Mock,其中包括Google Test。 I have added another project (called Tests) to the Visual Studio Solution. 我已经在Visual Studio解决方案中添加了另一个项目(称为“测试”)。 The units to test are in another project called Main. 要测试的单元在另一个名为Main的项目中。 The plan is to add each cpp file that I want to test to the Tests project. 计划是将我要测试的每个cpp文件添加到Tests项目。 The Tests project has access to all header files from Main. Tests项目可以访问Main中的所有头文件。

I have added one cpp file to the Tests project, and it compiles, but comes up with linker errors. 我已经将一个cpp文件添加到Tests项目中,并且可以编译,但是出现了链接器错误。 Most are because of a class derived from COleDateTime, called CTimeValue. 大多数是因为从COleDateTime派生的类称为CTimeValue。 The unit under test has methods with pass-by-value CTimeValue parameters and also declares some CTimeValue attributes. 被测单元具有带有传递值CTimeValue参数的方法,并且还声明了一些CTimeValue属性。

I want to test the UUT in isolation, and use mocks and fakes for all dependencies. 我想单独测试UUT,并为所有依赖项使用模拟和伪造品。 I don't see how to do it with CTimeValue. 我看不到如何用CTimeValue做到这一点。 It is used as a value, contains no virtual methods, but is still quite complex and would deserve a seperate unit test. 它用作值,不包含任何虚拟方法,但仍然相当复杂,应该进行单独的单元测试。

CTimeValue is only one of many classes that is like this in the project. CTimeValue只是项目中类似的许多类之一。 How can I isolate the testing of classes that use these user-defined types? 如何隔离使用这些用户定义类型的类的测试?

Cheers, Felix 干杯,菲利克斯

Sometimes one can not simply mock things. 有时不能简单地嘲笑事物。 In that case what you can do is have a comprehensive test for the class in question (CTimeValue) and make sure you run the tests for that class as a subsuite in your other test. 在这种情况下,您可以做的是对所涉及的类(CTimeValue)进行全面的测试,并确保以该类的测试作为子集在其他测试中运行。

Mocks are most suitable for working with objects that provide services for each other, the expectations on the mocks describe their relationships. 嘲笑最适合用于为彼此提供服务的对象,嘲笑的期望描述了它们之间的关系。 There's not much point in mocking value objects. 嘲笑值对象没有多大意义。

Using a mock object you only need to add the method signatures that your UUT uses so maybe you can create a mock using google mock. 使用模拟对象,您只需添加UUT使用的方法签名,这样您就可以使用Google模拟创建模拟了。 Of course you will need a separate test suite for the CTimeValue class, and if you have that then it is probably better to link in the actual object. 当然,您将需要为CTimeValue类提供单独的测试套件,如果有,则最好将其链接到实际对象中。 You need to decide if it is worth the effort to create an interface class to create the mock from. 您需要确定是否值得创建一个接口类来创建模拟对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM