What is the difference between a unit and integration test? Consequences of using dependencies in your unit tests.
(SpaceX rocket explodes on landing. No astronauts were injured in the taking of this photo).
Integration Tests
Integration tests check if everything is working together. Imagine a series of cogs working together in a watch. An integration test would be: is the watch telling the correct time? Is it still telling the correct time in 3 days?
All it tells you is whether the overall piece is working. If it fails: it doesn’t tell you exactly where it is failing.
Unit Tests
These are really specific types of test. They tell you whether one specific thing is working or failing. The key to this type of test is that it tests only one specific thing while assuming that everything else is working just fine. That’s the key point.
Example: Let’s elaborate on this point using an example:
- Let’s take a car as an example.
- Integration test for a car: e.g. does Car drives to Echuca and back. If it does this, you can safely say that a car is working from an overall view point. It is an integration test. If it fails you have no idea where it is actually failing: is it the radiator, transmission, engine, or carburettor? You have no idea. It could be anything.
- Unit test for a car: That the engine is working. This tests assumes that everything else in the car is working just fine. That way if this particular unit test fails: you can be very confident that the problem lies in the engine – so you can quickly isolate and fix the problem.
The consequences of mixing your integration and unit tests:
-
Suppose your car integration test fails. It doesn’t drive successfully to Echuca. Where is the problem?
- You look in your engine test. But in this particular case, the engine test uses external dependencies: it uses a special fuel system. Let us suppose the engine unit test has also failed. Where then is the problem? (Give yourself 10 seconds to get the answer.)
- Did the engine fail, or was it the fuel system that caused the engine to fail?
You see the problem here? You don’t know what exactly is failing. If you use 10 dependencies, then every single one of those 10 could have caused the problem – and you won’t know where to start. That’s why unit tests mocks to assume that everything else is working just fine.
Second Example:
Integration test: Fly a man to the moon and return him safely. Unit test: The booster rocket test whether they fire. This test assumes everything else is working fine.
Suppose the integration test fails for the space shuttle and the booster rocket unit test also fails. Now you know exactly where the problem is.
Hope this helps.