Is it easy to test a Flutter widget?

In the previous article I talked about the importance of unit test your code, if you didn’t see that one I am leaving the link over here. And continue talking about the same topic, I would like to show how easy and important is test your ui, so let’s use the same example from the last article to write some ui tests.

As I said before, we are going to use the same project example that I created on the unit test article, and because of that I really encourage you to take a look on that. Ok, to test a widget the first thing to do is create a way to identify it, in order to find it in the widget tree, and to do that let’s give some a key on the FloatingActionButton widget as the image below shows.

Key

All right, and now you just have to create the counter_test_widget.dart file to be able to write the widget tests, like the image below.

Counter Test Widget

As we can see the widget test code is testing the same scenario as the unit test on the previous article, however we have a few differences… so let’s understand what's going on.

First we the same structure, which is a group of tests with the purpose of testing the increment function, but now we receive as a parameter the WidgetTester which contains our widget tree. One thing to pay attention is that the function must be async because we need to wait for the widget to be built.

Now for the first scenario you need to call the function pumpWidget(), in order to execute the app and render the UI, attention that you have to put the MyApp() widget to initialise all the tree. So now the next step is find if some widget has the 0 value as String.

And for the second scenario we have to execute the initial steps and then try to find this FloatingActionButton widget by the key and execute the click action using the tap function, and to ensure the action was executed we need to call the pump() function in order to make the code wait for a moment before we try to find some widget with the 1 value as String.

And now is the final step, execute the tests using the command “flutter test test/counter_test_widget.dart” on the terminal.

Executing Tests

Test the UI is pretty simple with Flutter and it’s a good way to complement your tests after write the unit tests, and with these two test types you will certain ensure more quality of your app. I hope you enjoy these two articles talking about test your Flutter app.

A simple Flutter dev learning everyday.