Video in progress
Explain the main difference between a unit test and an integration test with an example.
A unit test checks one class without its dependencies, while an integration test checks that several parts work together, for example a service, a repository and a real database. The first is fast, the second slower but finds real problems.
📖 Answer
You can test the same feature in two ways.
Unit: you take UserService and mock UserRepository. The test checks the logic "if the email is taken, is an exception thrown?" 5 ms.
Integration: the Spring context starts, PostgreSQL runs in a container, UserService.register() is called, and you check that a row appeared in the database. 2-5 seconds.
| Unit | Integration | |
|---|---|---|
| What takes part | one class | several layers, real infrastructure |
| Speed | ms | seconds |
| What it finds | logic errors | configuration, SQL, mapping, transaction errors |
| When it fails | the cause is clear | you have to hunt for the cause |
A unit test tells you "is the if condition right?", but only an integration test catches that you misspelled a unique constraint name, or that a @Column name doesn't match the column in the database. You need both, and the ratio depends on the project.
Sign up to mark studied questions and save your progress.