Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit Testing without Assertions

Occasionally I come accross a unit test that doesn't Assert anything. The particular example I came across this morning was testing that a log file got written to when a condition was met. The assumption was that if no error was thrown the test passed.

I personally don't have a problem with this, however it seems to be a bit of a "code smell" to write a unit test that doesn't have any assertions associated with it.

Just wondering what people's views on this are?

like image 480
lomaxx Avatar asked Sep 26 '08 02:09

lomaxx


People also ask

Why are assertions used in unit testing?

Assertions replace us humans in checking that the software does what it should. They express the requirements that the unit under test is expected to meet. Assert the exact desired behavior; avoid overly precise or overly loose conditions.

Why is it best practice to only have one assertion in a test?

Using multiple assertions in a single test means that your test is more complicated and will be harder to get right. The wrong way of using the multiple asserts in your test function: arrange the system under test.

Should unit tests only have one assertion?

To keep unit tests simple, it is best to include a single assertion in one test method. That means, one unit test should test one use-case and no more. Now, QAs may try to test all aspects of a module with multiple assertions in one method so as to cover more features in one test.

How many assertions should a unit test contain?

Don't have more than one assert that depends on the side-effects of previous execution. Group assert s together that test the same function/feature or facet thereof--no need for the overhead of multiple unit test cases when it's not necessary.


2 Answers

It's simply a very minimal test, and should be documented as such. It only verifies that it doesn't explode when run. The worst part about tests like this is that they present a false sense of security. Your code coverage will go up, but it's illusory. Very bad odor.

like image 143
David M. Karr Avatar answered Sep 28 '22 19:09

David M. Karr


This would be the official way to do it:

// Act Exception ex = Record.Exception(() => someCode());  // Assert Assert.Null(ex); 
like image 22
Brad Wilson Avatar answered Sep 28 '22 19:09

Brad Wilson