thassan
thassan

Reputation: 401

Should we test src code assertions (NOT exceptions) in C++ unit test?

I have heard conflicting views from several people in this regard, and wanted to see what the stackoverflow community thinks about this.

The people in the yes side says:
- We should test assertions , since it gives us code coverage
- What if tomorrow some new programmer comes and takes out the assertion by mistake, and if there is no test to catch it. We should be testing assertions as such.

The people on the no side says
- I don't see how it is helpful to test when the program exits and testing this is fairly expensive. For example, in google test framework, we fork a child process and run the death test there and make the parent process to wait for result for child process. This is fairly expensive testing. In a multithreaded environment testing assertions are more expensive. As such this kind of expensive testing which gives such minimal value is not worth it.
- If there is a code path that leads to assertion in src, during build/run time we will catch that and get the stack trace. As such , we will have all the information needed to debug as to why the assertion is being hit. As such creating unit tests that only tests basic assertions is not really helpful.

So, should we test src code assertions (NOT exceptions) in C++ unit test?

Upvotes: 0

Views: 102

Answers (2)

piotrek
piotrek

Reputation: 14550

- We should test assertions , since it gives us code coverage

coverage is not the purpose of testing. the purpose is to feel secure when doing the refactoring. do you write tests also for setters and getters?

- What if tomorrow some new programmer comes and takes out the assertion by mistake, and if there is no test to catch it.

if your contract says the code must throw an exception then you should test if that exception is thrown. but assertions are usually written to fail-fast and better document the code. if assertion failed then the code before assertion is broken. tests for completely different component should discover that bug.

so in my opinion you should test business behavior/interface of your code, not the implementation details. this will make maintenance of your tests way cheaper

Upvotes: 1

BЈовић
BЈовић

Reputation: 64283

In my opinion, instead of using assert, which just aborts the program, throw an exception. That you can unit test easily.

Now to answer the question : no, there is no point in unit testing the assert, as it is meant to be a forbidden case. If an assert fails, you will notice it right away (the program's execution will stop).

Upvotes: 0

Related Questions