Article Image

Test Widget in Flutter

25th February 2019

Hi everybody!

In this post we are going to see how test our widgets.

We suppose we have a User with images and we need show them in a collection. In this case, we have a GridView with Images like children. Something like this:

NOTE: userImages is a simple collection of URLs for simplify example.

As a good practice is very important test our code in whatever layer. So, we need add flutter test dependency if not present in pubspec.yaml file:

1dev_dependencies:
2flutter_test:
3sdk: flutter

Our first use case will be if “there is no images then show empty container”, then we need create a test like the following code:

Run code and green, good for us!. We have test in our code and if we make some change in view, the test will tell me if something went wrong.

In that first test, we test only return Container();. Now, we are going to test the following piece of code:

For that, we can write a new test:

Run test and ….. red!. Something went wrong!. But what could be wrong? … Error message was: package:flutter/src/painting/basic_types.dart: Failed assertion: line 222 pos 10: textDirection != null: is not true.

We didn't some text or something like that. What is happen here?

After some attempts and few hours, I find the solution. Flutter has a widget called MaterialApp which initialize some widget for you, so we need wrap our UserImagesView in a MaterialApp only for test.

Then, we test looks like:

Run test and ….. red again!. Oh god! What is happen here!? Why do you hate my test!?. Don't worry, in this time the error message is very clear: Exception: HTTP request failed, statusCode: 400.

We are using Image.network and in fact, we are wrong in this case. We must not depend on external services in our test, this is a bad practice.

In order to make green our test, we need mock all call to internet. For that, add the following dependency:

1image_test_utils: ^1.0.0

Now, we can use provideMockedNetworkImages method which mock HttpClient for us and the code will be:

Finally, all green and our widget are tested!.

That's all folks!

Enjoy!

More Than Code LLC

Address: 8 The Green STE B, Dover, DE 19901

Phone: +1 856-786-4408

Contact: team@mtc-flutter.com

© Copyright 2022 All right reserved to More Than Code LLC