Skip to content

Testing

Abdul Malik edited this page Aug 23, 2021 · 1 revision

The implementation as well as the file structure for the tests will be similar to the guidelines of the stacked architecture.

File Structure

The top-level test folder will contain 2 folders.

  • Setup

    The setup folder will have 2 files,

     test_data.dart to keep the expected results of the tests.

     test_helpers.dart to remove duplicate code needed to setup the tests. As well as mocking and stubbing Services.

  • Service_tests

    Naming convention used will be service_name_test.dart the " _test " is important as it helps Flutter recognize it is a file that contains tests.

    This folder will contain all tests related to services.

  • ViewModel_tests

    This folder will contain all tests related to ViewModels.

  • Widget_tests

    This folder will contain all widget tests.

|-- test
|   |
|   |-- setup
|   |   |
|   |   |-- test_data.dart
|   |   |
|   |   '-- test_helpers.dart
|   |
|   |-- service_tests
|   |   |
|   |   '-- api_service_test.dart
|   |
|   |-- viewmodel_tests
|   |   |
|   |   '-- profile_viewmodel_test.dart
|   |
|   |-- widget_tests
|   |   |
|   |   '-- ViewName_view_test.dart

The mockito dart package is used to implement the test functionality in the application.

Testing Conventions

  • File name being tested should be known
  • Function being tested should be known
  • Assumption of test should be known
  • Corresponding expected result of test should be known

Example

This code snippet is a part of the Pull Request(#120) merged in the project's repository on 29th March 2021.

void main() {

  group('ApiServiceTest -', () {

    group('Update history -', () {

      test( 'When update history network call made, should populate history items', () async {

        final api = getAndRegisterApiServiceMock();
        GeneralFeatures general = GeneralFeatures();

        //Set static DateTime for test
        CustomizableDateTime.customTime = DateTime.parse("1969-07-20 20:18:04");

        //Mock Api Call
        await ApiRequests.updateHistory(api, general, MockBuildContext());

        //Expect [general.historyItems] to not be null
        expect(general.historyItems, isNotNull);

        //Expect [general.historyItems.runtimeType] to be same
        expect(general.historyItems[0].runtimeType,
            TestData.historyItems[0].runtimeType);

        //Set back to dynamic
        CustomizableDateTime.customTime = null;

      });

    });

  });

}

When the command flutter test is run in the terminal this is what's displayed in the terminal.

ApiServiceTest - Update history - When update history network call made, should populate history items

testing pic

Thus, if a test fails the point of failure can be narrowed down substantially.

Resources

Articles

Videos