How to Generate Realistic Test Data using Faker in Flutter

Flutter Jun 23, 2023

Writing reliable tests to ensure our application functions correctly is very important. We can strengthen our tests by using generated realistic test data. For example, when users register themselves on our application, the data they provide is random. Of course, as developers, we can set boundaries for the excepted data. But we want to make sure those boundaries are tested.

Example

When testing an email field, there are many different valid and invalid email formats to consider. It would be difficult and time-consuming to manually list all the possible variations in a test, and we might accidentally overlook certain types of emails. However, we can simplify this process by using a fake data generator. This tool allows us to generate random and diverse email addresses, giving us a wider range of scenarios to test. By including these unpredictable inputs in our tests, we can ensure that we cover unexpected data, similar to what our users might enter. This approach improves the reliability and robustness of our tests.

What is Faker?

The faker package is a well-known package in Flutter that generates fake data. It offers a wide range of functions that allow developers to generate randomized realistic data. Let us explore some of the possibilities for fake data that the faker package can generate:

  1. Generating Names: The package allows you to generate random names, including first names, last names, and full names.
  2. Generating Addresses: You can generate random addresses, including street addresses, cities, states, ZIP codes, and countries.
  3. Generating Contact Information: The package can generate random phone numbers, email addresses, and usernames.
  4. Generating Text: It provides functions to generate random sentences, paragraphs, or blocks of text, which can be useful for populating text fields or generating sample content.
  5. Generating Dates and Times: You can generate random dates, times, and timestamps using the package. It supports various formats and allows you to generate dates within a specific range.
  6. Generating Internet-related Data: You can generate URLs, passwords, IP addresses, and more.  

These are just a few examples of the functionalities provided by the faker package. It offers many more options for generating fake data. You can refer to the package's documentation for more information.

Generating test data using Faker

Now that we know what the faker package can do let us install it and go over a practical example.

Installing the faker package

To get started, let us install the package by executing flutter pub add faker --dev.

After executing the command, make sure that the package is included under the dev_dependencies section in your pubspec.yaml file.

dev_dependencies:
  faker: ^2.1.0
  flutter_test:
    sdk: flutter

Once the package is installed, we can start implementing the faker package.

Implementing the faker package

For the implementation, we will be testing thevalidateEmail function of our AuthenticationPage, see the code below:

class AuthenticationPage extends StatelessWidget {
  const AuthenticationPage({super.key});

  String? validateEmail({required String? value}) {
    if (value!.isEmpty) {
      return 'This field cannot be empty.';
    }

    if (RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$').hasMatch(value) == false) {
      return 'This is not a valid email address.';
    }

    return null;
  }

  @override
  Widget build(BuildContext context) {
    return const Scaffold();
  }
}

In the validateEmail function we are using a regular expression to check if the provided email address is a valid email. For this function, we have the following tests:

import 'package:codeonwards_demo/main.dart';
import 'package:flutter_test/flutter_test.dart';

void main() {
  const authenticationPage = AuthenticationPage();

  group('email', () {
    test('it returns an error message when email is not valid', () {
      final emailMissingDot = authenticationPage.validateEmail(
        value: 'codeonwards@testcom',
      );

      expect(emailMissingDot, 'This is not a valid email address.');
    });

    test('it returns null when a valid email address is provided', () {
      final actual = authenticationPage.validateEmail(
        value: '[email protected]',
      );

      expect(actual, null);
    });
  });
}

In this test file, we are currently using hardcoded email addresses. We want to replace them with generated fake email addresses from the faker package.

To start, we need to import the faker package. After that, we can create an instance of the Faker class. Now that we have the instance we can call the email() function on the internet property of our faker instance to generate an email address.

import 'package:codeonwards_demo/main.dart';
import 'package:faker/faker.dart';
import 'package:flutter_test/flutter_test.dart';

void main() {
  const authenticationPage = AuthenticationPage();
  final Faker faker = Faker();

  group('email', () {
    test('it returns an error message when email is not valid', () {
      String emailMissingDot = faker.internet.email().replaceAll('.', '');
      print(emailMissingDot);

      final resultEmailMissingDot = authenticationPage.validateEmail(
        value: emailMissingDot,
      );

      expect(resultEmailMissingDot, 'This is not a valid email address.');
    });
    
    test('it returns null when a valid email address is provided', () {
      String email = faker.internet.email();
      print(email);

      final actual = authenticationPage.validateEmail(
        value: email,
      );

      expect(actual, null);
    });
  });
}

In this code snippet, we generate two fake email addresses one for every test. For the first test, we want to replace the . to make sure that we have an invalid email address. For the second test, we generate a valid email address. Also, for demonstration purposes, we added print statements to show what the generated emails look like.

flutter_running_our_tests_with_generated_faker_data

As you can see both tests are still successful and our print statements printed the following email addresses:

oswald_sawayn@jonesbiz
[email protected]

Before this change, the tests were always using .com email addresses. With the fake email addresses generated by faker, we will test different domains. Other than that the generated email address also uses special characters.

Conclusion

The faker package in Flutter is a helpful tool for generating fake test data. It allows us to generate randomized realistic data, which improves the accuracy and coverage of our tests. By using faker, we can simulate different scenarios and identify potential problems in our code. This helps us make our application more reliable and ensures that it works well with unknown data.

Tags