Code Under the Microscope: Rethinking Java Testing and ORM with JUnit 5, Mockito, and JPA
As backend developers, we often rely heavily on tools like Postman for End-to-End (E2E) testing. While useful, they are notoriously slow. Worse, when a test fails, it becomes a guessing game: is it a faulty SQL query, or a bug in the service logic?
Tools like Postman and APIFox belong to end to end (E2E)testing.they are very slow.When a test fails,we don't know if i's an SQL error or a Service logic error.
The purpose of unite testing is isolation.It puts a single class under a microscope.Without connection to a database or starting a Tomcat server,it simply verifies whether the if-else branches an thrown exceptions inside the class work as expcted.
What is Mocking? Since we are not connecting to a real database, how do we handle method calls like userMapper.selectById() inside UserServiceImpl? Will it just throw a NullPointerException? This is where the Mockito framework comes in. The word 'Mock' literally means 'to simulate' or 'to fake'. Think of it like testing whether a motherboard interface works properly: you don't need to plug in a real hard drive full of data; you just need to plug in a 'signal generator'. Mockito is exactly that signal generator.
Assertion For methods that return a value: We typically use assertions like assertNotNull, assertEquals, etc., to validate the returned data.