Flutter has 3 types of test
- Unit Test
- Widget Test
- Integration Test.
Unit Test: Tests a single function, method or class.
Widget Test: Test a single widget or flow of Widgets.
Integration Test: Tests complete appication or a large part of an application.
Widget tests run headless in the console; hence, they miss the environment while testing. Integration tests are widget tests that require a device to run. It can be a physical device or a simulator. With Integration tests, you can test the widgets and the environment where the app is running.
Here is the CMDE Table - Confidence Maintenance Dependencies Execution Table This table lets us know the values of each test in the given segment. As you can see, the Unit test has the lowest confidence as you test a small function or a call. Whereas the Integration test has the Highest Confidence as you are trying an Entire widget with a given environment.
It’s easy to maintain unit tests compared to widget and integration tests. We will see the reasons later on.
The Dependencies management in the unit test is few and is the most in the Integration test.
Finally, Execution - Unit Tests are executed very quickly, saving a lot of time while running. And Integration tests consume the most time while running as it installs the entire application on the device and then test it.
As you saw in the CMDE table, Unit tests are the fastest but have less code coverage. Widget tests are medium in time-consuming but do not test the environment; only the widgets are tested. Integration tests are slow but have the highest code coverage and result. Integration also tests the environment where the app is running, giving out the most accurate result.
Now how will you decide which tests to run and when? Many developers say it’s just enough to run widget tests and ignore unit and integration tests to have the best of both. But that’s not how TDD works.
You should write a unit test after the code completion of every function. Widget test when you write a widget and Integration test before you create a PR to merge into the main or develop branch. So that every code that is getting merged, has the highest test coverage and result.