Unit Testing in Flutter

Lets add unit tests to your flutter application.

Unit tests are handy for verifying the behavior of a single function, method, or class. The test package provides the core framework for writing unit tests, and the flutter_test package provides additional utilities for testing Widgets.

So I have set up a basic Login form with email field, password field, and the login button. On login button click the form is validated that the email and password are not empty.

Login Screen

To validate the form let’s create a FieldValidator class which have two menthods validateEmail and validatePassword .

FieldValidator class

So let’s create a new file under test directory named email_password_validator_test.dart .

Let’s write some tests !

import 'package:exploreflutter/utils/validator.dart';
import 'package:test/test.dart';

void main() {
test('Empty Email Test', () {
var result = FieldValidator.validateEmail('');
expect(result, 'Enter Email!');
});
}

Now let’s Test this .

Test Passed

It worked !

Add another test and Test it

import 'package:exploreflutter/utils/validator.dart';
import 'package:test/test.dart';

void main() {
test('Empty Email Test', () {
var result = FieldValidator.validateEmail('');
expect(result, 'Enter Email!');
});


test('Invalid Email Test', () {
var result = FieldValidator.validateEmail('');
expect(result, 'Enter Valid Email!');
});

}
Test Failed

The second test failed as we have passed an empty string to validateEmail and we Expected result ‘Enter Valid Email!’ but it should be ‘Enter Email!’ .

Let’s Fix this and add few more Test .

import 'package:exploreflutter/utils/validator.dart';
import 'package:test/test.dart';

void main() {
test('Empty Email Test', () {
var result = FieldValidator.validateEmail('');
expect(result, 'Enter Email!');
});

test('Invalid Email Test', () {
var result = FieldValidator.validateEmail('');
expect(result, 'Enter Valid Email!');
});

test('Valid Email Test', () {
var result = FieldValidator.validateEmail('ajay.kumar@nonstopio.com');
expect(result, null);
});

test('Empty Password Test', () {
var result = FieldValidator.validatePassword('');
expect(result, 'Enter Password!');
});

test('Invalid Password Test', () {
var result = FieldValidator.validatePassword('123');
expect(result, 'Password must be more than 6 charater');
});

test('Valid Password Test', () {
var result = FieldValidator.validatePassword('ajay12345');
expect(result, null);
});
}

We can also run these Test with in Android Studio as well .

Run Test in Android Studio

Let’s fix the second test and run it again .

test('Invalid Email Test', () {
var result = FieldValidator.validateEmail('ajay');
expect(result, 'Enter Valid Email!');
});
All Test Passed