Flutterexperts

Empowering Vision with FlutterExperts' Expertise
Automation Testing In Flutter

Google recently announced that more than over 2 million Developers Worldwide have laid their hands on Flutter. After the language’s roll-out at the Google I/O ’18, This revelation from the search giant immensely Signifies diversion of developers from Native development to the Newer Technologies Building Extensive Cross-Platform Apps. Flutter started its life as an open-source UI framework that helps developers build native interfaces supporting different device sizes, pixel densities & orientations creating a magnificent digital experience.

In this article, We will have a look at How to do Automation Testing in a project through the help of fluttering its features and customisation available:

Introduction to Automation Testing:

Testing Apps with Multiple Features is Quite Cumbersome on manual Testing. Therefore, Automation Testing comes in place ensuring the tested app is not Error-prone before publishing it. Keeping into Consideration the bug solving speed and feature Intended in the Apps are not at all Compromised. Automation Testing is Quite Eventful for large scale apps were manually testing each feature might not be suitable.

Necessity of Testing?

Testing serves as a vital part of mobile application development in finding bugs & errors promptly making sure that the application works perfectly in future with the requirements :

  • It’s a vital factor in the development process that brings to market a high-quality product.
  • It helps to guarantee an in-depth analysis of functionality.
  • The testing process requires precise planning and execution

The Flutter framework provides comprehensive support for Automation Testing of Mobile Apps.

What Comprehends Automation testing?

Automation Testing is a software testing technique making sure the requirements meet the results. Testing is done by writing testing scripts with test cases. As we know that app nowadays is multi-featured apps making it rigorously difficult to test apps but this problem is removed by Automation Testing in Flutter which makes sure your app is bug-free & Performant.

Automated testing falls into three categories mainly:

We will try to explain all about Unit and Widget Testing in the Blog with the second part of the Blog explaining about Integration testing in Flutter.

Unit testing

Unit refers to a single unit referring to testing up a single module or a class making sure the basic functionality works on multiple conditions.

  • Writing Unit tests will require the addition of test package.
  • Using a TextField Validator Class containing validator methods for email & password validation. The file can be seen in the demo by the name as Validator.dart
import 'package:automation_testing_module/utils/constants.dart';class Validator {
//email validation method
static String validateEmail(String value)
{
String pattern = r'^(([^<>()[\]\\.,;:\s@\"]+(\.
[^<>() [\]\\.,;:\s@\"]+)*)'r'|(\".+\"))@((\[[0-9]{1,3}\.
[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])'r'|(([a-zA-Z\-0-9]+\.)
+[a-zA-Z]{2,}))$'
;RegExp regExp = new RegExp(pattern);
if (value.isEmpty) {
return Constants.ENTER_EMAIL;
}
if (!regExp.hasMatch(value)) {
return Constants.INVALID_EMAIL;
} //returns null when valid return null;
} // password validation method static String validatePassword(String value) {
Pattern pattern =
r'^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[!@#\$?^&*~]).{8,}$';
RegExp regex = new RegExp(pattern);
if (value.isEmpty)
return Constants.ENTER_PASSWORD;
else if (value.length < 8)
return Constants.INVALID_PASSWORD;
else if (!regex.hasMatch(value)) return Constants.INVALID_FORMAT_PASSWORD;
return null;
}
}
  • Creating a class under test directory by name unit_test.dart.
import 'package:automation_testing_module/utils/constants.dart';
import 'package:automation_testing_module/utils/validator.dart';
import 'package:test/test.dart';
void main() {

//Email validation test
test('Email Not Entered Test', () {
var result = Validator.validateEmail('');
expect(result, Constants.ENTER_EMAIL);
});
test('Invalid Email Entered Test', () {
var result = Validator.validateEmail('akshay@aeologic');
expect(result, Constants.INVALID_EMAIL);
});
test('Valid Email Entered Test', () {
var result = Validator.validateEmail('akshay@aeologic.com');
expect(result, null);
});
  //Password validation test
test('Password Not Entered Test', () {
var result = Validator.validatePassword('');
expect(result, Constants.ENTER_PASSWORD);
});
test('Invalid Password Entered Test', () {
var result = Validator.validatePassword('1234567');
expect(result, Constants.INVALID_PASSWORD);
});
test('Invalid Password Format Entered Test', () {
var result = Validator.validatePassword('unittest');
expect(result, Constants.INVALID_FORMAT_PASSWORD);
});
test('Valid Password Test', () {
var result = Validator.validatePassword('Unittest@123');
expect(result, mull);
});
}

Above can be found is written test for Multiple Test Cases.

Run Using the following command at Terminal by:

flutter test test/unit_test.dart

Refactoring:

  • the test function is called which will create a test case with the given description and body, there are also other properties of test functions which can be used as needed but these two are appropriate to run the test.
  • We called validateEmail() method by giving null value and storing it in the result variable afterwards.
  • expect() method keep an eye whether the value passed and the expected value is similar.

Widget testingWidget Testing corresponds to the testing of the Widgets on certain circumstances which means how the widget responds on any particular event and how a widget is altered on an event occur.

  • Adding flutter_test package in pubsec.yaml. The package provides additional utilities for testing Widgets.
  • Herewith In the demo, Login Page consisting of text fields for namely email and password field is present with a Material Button. The event will occur on the tap of Material Button click event namely widget_testing_view.dart.

Code Implementation:

/media/1bccf15a228a804095203c33a34bd37d

  • If Entered data is valid and the login button is pressed a text widget will show the Valid data text.
  • Using the above widget for testing by creating a test class for the purpose namely widget_test.dart.
  • We will use the above widget for the testing and create a testing class for it named widget_test.dart
import 'package:automation_testing_module/view/widget_testing_view.dart';
import
'package:flutter/material.dart'
;
import
'package:flutter_test/flutter_test.dart'
;
void main() {testWidgets('Login Successful',(WidgetTester widgetTester) async {

//Renders the UI from the given widget
await widgetTester.pumpWidget(LoginWidget());// Widget finders using key & type
final emailTextFieldFinder = find.byKey(Key('emailKey'));
final passwordTextFieldFinder = find.byKey(Key('passwordKey'));
final buttonFieldFinder = find.byType(MaterialButton);//enters text to the TextFormField using enterText
await widgetTester.enterText(emailTextFieldFinder,
'akshay@aeologic.com');
await widgetTester.pump();
expect(find.text('akshay@aeologic.com'), findsOneWidget);//enters text to the TextFormField using enterText
await widgetTester.enterText(passwordTextFieldFinder,
'Unittest@123');
await widgetTester.pump();
expect(find.text('Unittest@123'), findsOneWidget);//make the button click event
await widgetTester.tap(buttonFieldFinder);
await widgetTester.pump();//check for the response after button tap
final textFinder = find.text('Valid Data');
expect(textFinder, findsWidgets);

});
}

Run it by using the command flutter test test/widget_test.dart in Terminal.

Explanation:

Some prominently used methods are explained as:

  • testWidgets() function is used to create a widget test case as of test() is used in unit testing. But what it differs is the WidgetTester, it interacts with widgets and the test environment.
  • pumpWidget() function build and renders the provided widget in the test environment.
  • find() function searches for the widget using the Finder in flutter_test. The widgets can be searched using this.
  • pump() this function calls the setState() method in test environment and rebuild the widget.

So here how it goes, firstly we create a test using testWidgets() with the description and render the LoginWidget() in the test environment, once the widget is rendered the widgets are found by using the byKey() and byType() finders. Using the enterText() we input the text to the TextFormField, the button click event is called using the tap() in the test environment and if the Form validates the validDataFilled variable is set to true.

After this, we check for that the expected text is found in the widget.

Check out the demo code version on GitHub at:-

flutter-devs/Flutter_Automation_Testing
A new Flutter application. This project is a starting point for a Flutter application. A few resources to get you…github.com

Closing Thoughts

This article would serve as an Exploratory article for Flutter Testing and its working using Flutter. Automation Testing is an all- Important Tool in Large Scale Apps in native applications which has now also been introduced in flutter’s latest version also. This basically Ensures Deployment of the error Free version of the App & Decrease in Development time by Preventing any Undesirable errors to occur. Automation Testing is a must-case Scenario when it’s not practically possible to test each test case.

If you have not used Automation Testing, I hope this article has provided you with valuable information about what is all about Automation Testing, and that you will give it Automation Testing — a Try. Begin using for your apps !!

Feel free to connect with us:

And read more articles from FlutterDevs.com

FlutterDevs has been working on Flutter from quite some time now. You can connect with us on Facebook and Twitter for any flutter related queries.

We welcome feedback and hope that you share what you’re working on using #Flutter. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences!

Thank you for reading. 🌸

www.flutterdevs.com

Leave comment

Your email address will not be published. Required fields are marked with *.