Developing Unit tests for a Flutter application

TRUETECH is engaged in the development, support and maintenance of iOS, Android, PWA mobile applications. We have extensive experience and expertise in publishing mobile applications in popular markets like Google Play, App Store, Amazon, AppGallery and others.

Development and support of all types of mobile applications:

Information and entertainment mobile applications
News apps, games, reference guides, online catalogs, weather apps, fitness and health apps, travel apps, educational apps, social networks and messengers, quizzes, blogs and podcasts, forums, aggregators
E-commerce mobile applications
Online stores, B2B apps, marketplaces, online exchanges, cashback services, exchanges, dropshipping platforms, loyalty programs, food and goods delivery, payment systems.
Business process management mobile applications
CRM systems, ERP systems, project management, sales team tools, financial management, production management, logistics and delivery management, HR management, data monitoring systems
Electronic services mobile applications
Classified ads platforms, online schools, online cinemas, electronic service platforms, cashback platforms, video hosting, thematic portals, online booking and scheduling platforms, online trading platforms

These are just some of the types of mobile applications we work with, and each of them may have its own specific features and functionality, tailored to the specific needs and goals of the client.

Showing 1 of 1All 1735 services
Developing Unit tests for a Flutter application
Medium
~3-5 days
Frequently Asked Questions

Our competencies:

Development stages

Latest works

  • image_mobile-applications_feedme_467_0.webp
    Development of a mobile application for FEEDME
    792
  • image_mobile-applications_xoomer_471_0.webp
    Development of a mobile application for XOOMER
    671
  • image_mobile-applications_rhl_428_0.webp
    Development of a mobile application for RHL
    1097
  • image_mobile-applications_zippy_411_0.webp
    Development of a mobile application for ZIPPY
    969
  • image_mobile-applications_affhome_429_0.webp
    Development of a mobile application for Affhome
    914
  • image_mobile-applications_flavors_409_0.webp
    Development of a mobile application for the FLAVORS company
    495

Unit Test Development for Flutter Application

Flutter comes with flutter_test out of box, but writing good tests — not same as just writing tests. Typical Flutter project problem: tests exist, but test only "sunny day scenario," break on slightest structure change, or hold real HTTP requests inside.

Stack for Unit Tests

  • flutter_test — built-in, main
  • mocktail — preferable to mockito for Dart: no codegen required
  • bloc_test — for BLoC/Cubit
  • riverpod + ProviderContainer — for Riverpod-based logic
  • fake_async — testing code with Future.delayed and Timer

Testing BLoC

BLoC — most testable architecture in Flutter. bloc_test makes asserting state sequence trivial:

blocTest<AuthCubit, AuthState>(
  'emits [loading, authenticated] when login succeeds',
  build: () {
    when(() => mockAuthRepo.login(any(), any()))
        .thenAnswer((_) async => User(id: '1', name: 'Test'));
    return AuthCubit(authRepository: mockAuthRepo);
  },
  act: (cubit) => cubit.login('[email protected]', 'password'),
  expect: () => [
    const AuthState.loading(),
    AuthState.authenticated(User(id: '1', name: 'Test')),
  ],
);

If act needs delay or async — await cubit.login(...) inside act.

Testing Riverpod

ProviderContainer allows creating isolated environment with overridden providers:

test('userProvider returns user on success', () async {
  final container = ProviderContainer(
    overrides: [
      userRepositoryProvider.overrideWithValue(MockUserRepository()),
    ],
  );
  addTearDown(container.dispose);

  when(() => mockRepo.getUser('1')).thenAnswer((_) async => User(id: '1'));

  final user = await container.read(userProvider('1').future);
  expect(user.id, '1');
});

Testing Use Case and Repository

Use Case — pure business logic without Flutter dependencies. Tests simply:

test('GetOrderUseCase applies discount when user is premium', () async {
  when(() => mockOrderRepo.getOrder('order1'))
      .thenAnswer((_) async => Order(price: 100, isPremium: true));

  final result = await useCase.execute('order1');

  expect(result.finalPrice, 85);  // 15% discount
});

Common error: test Use Case via ViewModel/BLoC, not directly. Makes test fragile and slow.

fake_async for Code with Timers

test('debounce search fires after 300ms', () {
  fakeAsync((async) {
    final controller = SearchController();
    controller.query = 'flutter';

    async.elapse(Duration(milliseconds: 200));
    verifyNever(() => mockRepo.search(any()));

    async.elapse(Duration(milliseconds: 100));
    verify(() => mockRepo.search('flutter')).called(1);
  });
});

fakeAsync lets control time without actual sleep — tests with debounce/throttle run instantly.

Typical Errors

  • mocktail without registerFallbackValue for custom types — any() doesn't work with non-standard classes without registration
  • Tests that mutate global stateSharedPreferences or Hive in tests must initialize via SharedPreferences.setMockInitialValues({}) before each test
  • Missing tearDownProviderContainer.dispose() and StreamController.close() forgotten, tests leak memory

CI Integration

flutter test --coveragelcov.infogenhtml for HTML report. In GitHub Actions add step with flutter analyze + flutter test on each PR. For coverage filtering (exclude generated files) — remove_from_coverage package or sed filter on lcov.info.

Timeframe: 3–5 days depending on project volume and used architecture (BLoC / Riverpod / GetX).