C++单元测试中的覆盖初始化列表
我有一些我想单元测试的C ++代码:
class Example
{
private:
ExpensiveObject expensiveObject;
public:
Example() : expensiveObject() {
... constructor code
}
methodA() {
... some code
}
}
为Methoda
编写单元测试,我需要创建一个示例>示例
的实例。问题在于我不想初始化punchobject
,我想在单元测试中将其设置为null(我正在使用Google Test)。有办法做到吗?
I have some C++ code like this that I want to unit test:
class Example
{
private:
ExpensiveObject expensiveObject;
public:
Example() : expensiveObject() {
... constructor code
}
methodA() {
... some code
}
}
To write a unit test for methodA
I need to create an instance of Example
. The problem is that I don't want to initialize expensiveObject
, I would want to set it to null in my unit test (I am using Google Test). Is there a way to do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
昂贵的观点
无法分配null
。您可能想要的是将智能指针指向punchobject
,并拥有多个构造函数,或者您想更好地注入依赖项。现在您也可以测试无效的情况
expensiveObject
cannot be assignednull
. What you might want is to have a smart pointer toExpensiveObject
, and have multiple constructors or better you want to inject your dependencies.Now you can test it for null scenarios as well
我想不出任何方法,而没有稍微修改
示例
类的定义。但是,如果您可以忍受这样做,则有几种方法可以做到这一点:使用指针作为另一个答案进行依赖注入,或将类示为类,如下所示:live示例: https://godbolt.org/z/7e1rhwy4b
I can't think of any way to do this without slightly modifying the definition of the
Example
class. However, if you can tolerate to do this, there are several ways to do this: dependency injection using pointers as the other answer mentioned, or templatizing the class as shown below:Live example: https://godbolt.org/z/7e1rhWY4b