Write readable Flutter UI tests

Sander Kersten
2 min readMay 9, 2020

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:

Single test for all code. Set-up and tests mixed.

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:

Several test with duplicated set-up.

To avoid these problems and make small, focused tests without long, repeated set-ups, a common pattern is to use groups and a setUp function per group to do the set-up and have several tests per group, each with one (or a few) expects and verifys. For example:

Using nested groups to create focused tests without repeating set-up code.

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.