A unit test checks that one small piece of code works as expected. JUnit is the standard testing library for Java, and interviewers often ask freshers whether they have written tests.
A first test
Write a method that adds two numbers. In a test class, call the method with known values and use assertEquals to check the result. Run the test and see it pass. Then change the expected value and see it fail.
What to test
- The normal case, with typical input.
- Edge cases, such as zero, empty lists or very large values.
- Error cases, where an exception should be thrown.
Good habits
- Give each test a name that says what it checks.
- Keep each test short and focused on one behaviour.
- Run all tests before you push your code.
Next step: see our Java Full Stack course at ScholarLogic, or book a free demo class. A counsellor will share the fee and the next batch dates.
