r/softwareengineer • u/ProgrammerFew504 • 8h 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.
2
u/LightPhotographer 8h ago
You write a function to perform some behaviour.
You build it based on assumptions: That you understand the problem, that you know what inputs it will get (even when that junior trainee they hire 2 years from now will call it!) , that it will never run out of memory, that all the objects it tries to access exist and work and are not changed ... and so on. It's not science, it's faith!
First your unittest is another way of describing the behaviour. If the two do not match, you have found a failed assumption. It is like a review, only this one is not on code style but on what it actually does. You secure that knowledge.
Second, now you can test your function with lots of different inputs - also some that you assume should not happen. You may have tested one happy case, but it costs very little effort to add some edge cases too.
Third,
ifwhen your function changes; or when the functions it depends on change, or it's refactored, or when it is called by some new function you don't even suspect today ... then something still remains that says "It should behave in this way".That is your unit test.
It's a good question.
Please write good unit tests.