Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I write unit test for everything?

Tags:

I am wondering should I write unit test for everything. There are some classes is very difficult to write unit test. For example, I am writing some program for handling audio. The class for capturing audio from microphone, and class for play audio to speaker, how can I write unit test for those classes? I can't get output and input of those classes, so it is almost impossible to test them? The only test I can do is for getter and setter, those boring test. So the question is, what is the guide line for writing unit test? And how should I deal with these classes are difficult to test?

like image 996
Fang-Pen Lin Avatar asked Feb 05 '09 07:02

Fang-Pen Lin


People also ask

Should unit tests test all methods?

Unit Tests Should Only Test Public Methods The short answer is that you shouldn't test private methods directly, but only their effects on the public methods that call them. Unit tests are clients of the object under test, much like the other classes in the code that are dependent on the object.

Should unit tests mock everything?

TL;DR: Mock every dependency your unit test touches. This answer is too radical. Unit tests can and should exercise more than a single method, as long as it all belongs to the same cohesive unit. Doing otherwise would require way too much mocking/faking, leading to complicated and fragile tests.

Should unit tests cover all cases?

The purpose of a unit test in software engineering is to verify the behavior of a relatively small piece of software, independently from other parts. Unit tests are narrow in scope, and allow us to cover all cases, ensuring that every single part works correctly.

Are unit tests worth writing?

Unit testing ensures that all code meets quality standards before it's deployed. This ensures a reliable engineering environment where quality is paramount. Over the course of the product development life cycle, unit testing saves time and money, and helps developers write better code, more efficiently.


1 Answers

Use unit testing where it makes sense - don't aim for 100% coverage. The main guideline is to think rather than applying either dogma or laziness.

Having said that: If you have classes which are naturally hard to test, try to reduce how much they have to do. Isolate the untestable code and separate its API into an interface. Then test the logic which uses that API against a mock or stub.

like image 118
Jon Skeet Avatar answered Oct 19 '22 16:10

Jon Skeet