What are Unit Tests?
Unit tests are small programs designed to verify that each isolated part of your code (usually methods or functions) is working correctly.
The idea is to break the system down into units and ensure that each unit does exactly what it's supposed to.
Why use Unit Tests?
- Reliability – ensures your code works as expected.
- Bug prevention – if something breaks, you’ll find out quickly.
- Easier maintenance – future changes are less risky.
- Living documentation – tests describe how the code should behave.
Practical Example in Java
Imagine you have a simple function that adds two numbers:
Now, we write a unit test to check if the addition works:
The test runs add(2, 3) and expects the result to be 5.
If the code changes and breaks this logic, the test will fail, letting you know something is wrong.
Top comments (0)