断言在具有单元测试的C ++程序中的作用是什么? [英] What is the role of asserts in C++ programs that have unit tests?

查看:184
本文介绍了断言在具有单元测试的C ++程序中的作用是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在添加单元测试到一些遗留的C ++代码,我遇到了很多场景,其中一个函数内的断言将在单元测试运行期间跳闸。我经历的一个常见的成语是函数,它接受指针参数,并立即断言如果参数是NULL。

I've been adding unit tests to some legacy C++ code, and I've run into many scenarios where an assert inside a function will get tripped during a unit test run. A common idiom that I've run across is functions that take pointer arguments and immediately assert if the argument is NULL.

我可以很容易地解决这个禁用断言,当我单位测试。但我开始怀疑单元测试是否应该减轻运行时断言的需要。这是正确的评估吗?单元测试应该通过在管道中更快地发生来代替运行时断言(即:错误是在失败的测试中而不是在程序运行时捕获的)。

I could easily get around this by disabling asserts when I'm unit testing. But I'm starting to wonder if unit tests are supposed to alleviate the need for runtime asserts. Is this a correct assessment? Are unit tests supposed to replace runtime asserts by happening sooner in the pipeline (ie: the error is caught in a failing test instead of when the program is running).

On另一方面,我不喜欢添加软失败代码(例如 if(param == NULL)return false; )。

On the other hand, I don't like adding soft fails to code (e.g. if (param == NULL) return false;). A runtime assert at least makes it easier to debug a problem in case a unit test missed a bug.

推荐答案


如果单元测试错过了一个错误,运行时断言至少可以更容易地调试一个问题。

运行时断言至少可以在单元测试错过错误时更容易调试问题。

A runtime assert at least makes it easier to debug a problem in case a unit test missed a bug.

这是一个漂亮的基本点。单元测试不是要取代断言(IMHO是生成高质量代码的标准部分),它们是为了补充它们。

This is a pretty fundamental point. Unit tests are not meant to replace assertions (which IMHO are a standard part of producing good quality code), they're meant to complement them.

其次,有一个函数 Foo ,它声明它的参数是有效的。

在你的单元测试 Foo 你可以确保你只提供有效的参数,所以你认为你没关系。

6个月下来一些其他开发者将调用 Foo 从一些新的代码(可能有也可能没有单元测试),在那一刻,你会非常感谢你把那些断言。

Secondly, lets say you have a function Foo which asserts that it's parameters are valid.
In your unit test for Foo you can make sure you only supply valid parameters, so you think you're alright.
6 months down the track some other developer is going to call Foo from some new piece of code (which may or may not have unit tests), and at that point you'll be very grateful you put those asserts in there.

这篇关于断言在具有单元测试的C ++程序中的作用是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆