Skip to content

How to Widget Test (Work In Progress)

Xavier Chrétien edited this page Jul 7, 2020 · 4 revisions

⚠️ THIS PAGE IS A WORK IN PROGRESS ⚠️

Testing help reduces bugs and so increase considerably the stability of the application. And because everything is a widget in Flutter it's important to test these Widgets!

Before going any further, we recommend reading the Flutter series about widget testing.

In the next sections, we are going to explain how we test widget in this project.

Mock a service/manager

Widget testing is like a unit test for widgets so it's very important to test the widget on its own, without any services or manager acting. So to avoid any services/managers the widget could use we have to mock them using mockito. Here is the process:

1. Create the mock

Under the folder test/mock/services/ create a file called NAME_OF_THE_SERVICE_mock.dart and use the template below:

// FLUTTER / DART / THIRD-PARTIES
import 'package:mockito/mockito.dart';

// SERVICE
import 'package:notredame/core/services/service_file.dart';

// Mock for the NAME OF THE SERVICE service
class NameOfTheServiceMock extends Mock implements NameOfTheService {}

2. Add the function to register this service

We are using GetIt as service locator, so if the widget to test use services these had to be registered into the locator and so the mocked services! To register a mock on demands you have to add a new function into the helpers file following this template:

// OTHER
import 'package:notredame/locator.dart';

// SERVICES
import 'package:notredame/core/services/service_file.dart';

// MOCKS
import 'mock/services/name_of_the_service_mock.dart';

/// Load a mock of the [ServiceName]
ServiceName setupServiceNameMock() {
  unregister<ServiceName>();
  final service = ServiceNameMock();
  
  locator.registerSingleton<ServiceName>(service);

  return service;
}

3. Use the mock into a test file!

To use the mock you just add you just need to call added in the last point!