Write readable Flutter UI tests
Widget tests in Flutter often become hard to read and maintain for one of two reasons: One problem is that individual test check too many independent things. This makes it hard to see what exactly is being tested. It will also result tests requiring modifications whenever the widget being tested is changed. Silly example:
You might try to avoid that by making tests only check a single property. However, that way, you will probably repeat the same set-up code in many tests. Moving the set-up code into separate functions isn’t ideal either as it makes the tests harder te read. Yet another silly example:
To avoid these problems and make small, focused tests without long, repeated set-ups, a common pattern is to use group
s and a setUp
function per group to do the set-up and have several test
s per group, each with one (or a few) expect
s and verify
s. For example:
Unfortunately, for testing widgets this doesn't work. The setUp
functions don’t give you the tester
argument that testWidgets
gives you, so you can’t pump widgets or use tester
to perform gestures on the widgets in setUp
.
The flutter_test_ui package provides wrappers for setUp
and testWidgets
that allow you to use the same style for testing widgets:
All these example are pretty small, but especially for larger screens, where the test has to scroll first or tap somewhere to expand a piece of UI, this style of tests improves readability and maintainability a lot. I hope this package will allow you to make better and more tests.