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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With