Are assertions redundant when you have unit tests?

混江龙づ霸主 提交于 2019-12-23 13:25:19

问题


I'm not used yet to write unit tests and I want to do this on a full framework of little tools (making it more secure to use). That way I'll certainly learn more about unit tests than what I learnt until now.

However I'm really used to add assertions systematically everywhere I see there is a context to be sure about (that are removed in the final release). Mostly as preconditions in functions implementations and each time I retrieve informations that have to be correct (like C/C++ pointers validity for a famous example).

Now I'm asking : are assertions redundant when you have unit tests? Because it looks redundant as you're testing the behaviour of a bit of code; but in the same time it's not the same execution context.

Should I do both?


回答1:


Assertions that check preconditions can help detect and locate integration bugs. That is, whereas unit tests demonstrate that a method operates correctly when it is used (called) correctly, assertions that check preconditions can detect incorrect uses (calls) to the method. Using assertions causes faulty code to fail fast, which assists debugging.




回答2:


Assertions not only validate the code but serve as a form of documentation that informs readers about properties of various structures that they can be sure will be satisfied at that point in execution (e.g. node->next != NULL). This helps to create a mental model of the code when you're reading through it.

Assertions also serve to prevent disaster scenarios during runtime. e.g.

   assert(fuel);
   launch_rocket();

Trying to launch when there is no fuel might be disastrous. Your unit tests might have caught this scenario but it's always possible that you've missed it and an abort because a condition is unmet is Way better than a crash and burn during runtime.

So, in short, I'd keep them there. It's a good habit to add them and there's no gain in unlearning it.




回答3:


I would say that you need both. Unit tests test that your in-method asserts are correct ;)




回答4:


Unit testing and assertions are vastly different things, yet they complement each other.

Assertions deals with proper input-output of methods.

Unit tests deal with ensuring a unit works according to some governing rules, e.g. a specification. A unit may be ax method, a class, or a set of collaborating classes (sometimes such tests go by the name "integration tests")

So the assertions for a method square root are along the lines of the input and output both be non negative numbers. Unitests on the other hand may test that square root of 9 is 3 and that square root of some negative number yields an exception.



来源:https://stackoverflow.com/questions/4520847/are-assertions-redundant-when-you-have-unit-tests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!