Is it normal to have tests that are way bigger than the actual code being tested? For every line of code I am testing I usually have 2-3 lines in the unit test. Which ultimately leads to tons of time being spent just typing the tests in (mock, mock and mock more).
Where are the time savings? Do you ever avoid tests for code that is along the lines of being trivial? Most of my methods are less than 10 lines long and testing each one of them takes a lot of time, to the point where, as you see, I start questioning writing most of the tests in the first place.
I am not advocating not unit testing, I like it. Just want to see what factors people consider before writing tests. They come at a cost (in terms of time, hence money), so this cost must be evaluated somehow. How do you estimate the savings created by your unit tests, if ever?
You may come up with 100 tests just for those edge cases, which constitute less than 5% of the actual code. So, make sure to cover 100% of the 20% that defines critical paths, and at least 50% of the rest.
Testable code is code of high quality. It's cohesive and loosely coupled. It's well encapsulated and in charge of its own state. In short, it's singularly defined in its own proper place so that it's straightforward to maintain and extend.
The main objective of unit testing is to isolate written code to test and determine if it works as intended. Unit testing is an important step in the development process, because if done correctly, it can help detect early flaws in code which may be more difficult to find in later testing stages.
You might be testing the wrong thing - you should not have different tests for every method in your code.
You might have too many tests because you test implementation and not functionality - try testing how things are done test what is done.
For example if you have a customer that is entitled to get a discount on every order - create a customer with the correct data and create an order for that customer and then make sure that the final price is correct. That way you actually test the business logic and not how it's done internally.
Another reason is for big tests is lack of Isolation (a.k.a mocking) if you need to initialize difficult objects that require a lot of code try using fakes/mocks instead.
And finally if you have complicated tests it might be a smell - if you need to write a lot of code to test a simple functionality it might mean that your code is tightly coupled and your APIs are not clear enough.
Unit test code should follow the same best practices as production code. If you have that much unit test code it smells of a violation of the DRY principle.
Refactoring your unit tests to use Test Utility Methods should help reduce the overall unit test footprint.
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