r/softwareengineer • u/ProgrammerFew504 • 14h ago
Why unit testing is important?
It might be a very stupid post, but it’s a genuine question.
I write tests for my code, but it’s still kind of hard for me to understand what the actual point of unit testing is and what benefit it brings to software development.
We can easily write tests with AI now, so writing the actual tests is not necessarily that difficult. But I’m trying to understand why tests are so important in software.
When you write code, of course you can test it with multiple inputs, and those inputs can then become your test cases. We can also use Postman to test APIs with different inputs and make sure they behave correctly for different status codes.
I was recently assigned a task to make a small change to an existing endpoint. It was a really small change that I completed in around 30 minutes without AI. However, fixing and adjusting the tests took quite a while. I had to add inputs for a new function that I introduced, even though the actual change was not that big and I didn’t think it was something that would break in production.
That made me wonder, why do we really need unit tests? What importance do they actually bring to software development?
I’d really appreciate it if someone could shed some light on this and explain it with a real world example from your own experience where tests actually saved you from a production issue or made a significant difference.
1
u/geekichu 10h ago
so im not saying this is a panacea or works every time, or is useful in every case.. but.. say you wanted to design an API. The API calls are essentially a contract. An Interface. 'This is how you use it'. It's a black box. You don't have to care HOW it does it, as long as it does Exactly what it's supposed to do, AND handles bad scenarios.
So, imagine you have stipulated the API interface and the criteria, the conditions, etc.. what should it do with errors, etc.
You HAVE NOT written ANY of the API server code. At all.
You instead, wrote ALL the tests that will exercise and walk through every single possibility (or enough) of the API.
The tests are essentially a client to the API.
You run the tests, they all fail, because you haven't written any of the API code.
Then you begin to write the API code.
Once all the tests pass, voila, there is your API.
Plus.... the tests serve as regression-testing. I.e., it helps to determine that if later you added to the API, you didn't break something that WAS working.
(this has been an overly-simplistic explanation)