Good JUnit practice centers on writing small, independent, clearly named tests that verify one behavior each and don't rely on execution order or shared mutable state.
Key Points: • Keep each test focused on a single behavior so failures point directly at the cause. • Name tests descriptively, e.g. shouldThrowExceptionWhenAmountIsNegative(), so failures are self-explanatory in test reports. • Ensure tests are independent - one test's outcome or side effects should never affect another's. • Use @BeforeEach/@AfterEach for setup and teardown instead of duplicating boilerplate across test methods. • Favor real assertions over print statements, and prefer mocking external dependencies to keep tests fast and deterministic. • Treat test code with the same care as production code - refactor it, remove duplication, and keep it readable.
Example: Instead of one giant testUserService() method covering registration, login, and deletion, splitting it into three focused tests makes it immediately clear which behavior broke when a build fails.
Interview Tip: A concise interview answer is:
"I keep tests small and focused on one behavior, name them descriptively so failures are self-explanatory, and make sure they're independent of each other and of execution order. I also treat test code like production code - refactoring it and removing duplication instead of letting it rot."