In a web application, there are REST endpoints each of which make calls to various functions internally.
A simple API request and response test case can be written to test the functionality of that API.
Considering the scenario, where a developer makes some changes in a function required , the API test will fail and the developer will notice that it was his changes that caused the test case to fail . In the case of unit tests as well , the corresponding function test case will fail
So, what is the necessity of writing test cases for each function when an API test case will suffice. Please help me understand. Thanks for the time
There is more than one reason, so here is the ones I can think of:
When writing software, you always try to make your code modular and reusable.
Writing functions in general is already following that philosophy: You can reuse the function in many places throughout your code without writing duplicate code.
Unit testing functions enables you to test if that single function fulfills the contract that you expect from it, no matter where you use it.
This way, you can trust that function when you need to use it again at a later point in time, maybe with a new set of parameters that might make the function behave differently. You can effectively test all possible logical branches in that function seperately, even ones that you might not be using yet. (Thanks, @JBNizet)
This point gets even more obvious once you have to refactor your code.
When your API test fails, you don't know which part of code in your possibly complex application is causing the problem.
However, when the unit test for one function fails (which might cause the API test to fail as well), you know that the code in that very function is wrong. It saves you a lot of time.
API tests are exponentially harder to write, especially if they need to cover all possibilites of all functions called by the API.
This makes them a lot slower, too.
(Thanks again, @JBNizet)
Overall, it all boils down to the programming paradigm "divide and conquer": Break down any problem at hand into the smallest possible subproblems until only trivial problems (or in this case: unit tests) remain.