My new colleague incessantly insist me to count the number of times functions inside a unit test gets called when doing backend unit testing. I can see why it can be helpful at times but for most part I feel that it is redundant and unnecessary. From my perspective, it should not matter what function gets called and how many times it gets called. What matters is what goes in and comes out to check the expected behavior.
Unit testing should be more like a black box as in it doesnt matter how you get the answer, but matters if the answer is correct or not. If I am always validating the number of times some functions gets called, it creates a lot of overhead cost. It also means that everytime I change the approach to solve the problem, my unit test would break and I will need to fix it every single time. I feel like this approach limits the flexibility of coders.
Can anyone please tell me why these sort of unit testing should be performed? Thank you.
To be more specific, the code is in java and the overview of the structure is as follows: the controllers handles api calls and make calls to relevant facade, which in turn calls services to fetch the data. The facade is combination of services and the services talk to the database. These "unit tests" need to be performed for all three layers. Eg. checking the number of times each facade in the controllers gets called. And checking if each services inside the facade gets called and how many times it gets called.
Can anyone please tell me why these sort of unit testing should be performed?
Generally speaking, it should not. How many times a function is called is a private implementation detail. Unit testing tests public behavior of the unit, not it's private implementation.
As with every general statement there are exceptions: the number of times a method is called might be valuable in asserting whether the function of the component was correct. For example I once build a caching system, where you could put a cache in a pipeline and to check if it worked correctly, not only had the pipeline to deliver the correct result still, but the producer method should be called for input only once. If it was called multiple times, something was wrong with the implementation of the cache.
But as I said, that's a reasonable exception. Generally speaking, how many times a method is called is not a test criteria.
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