Skip to main content

10 - Flutter Integration Tests and DevTools: From Test to CI

How to write a Flutter integration test on the real app, measure frames in profile mode, use DevTools and run it in CI on Linux with xvfb.

What do you think about this article?

At a Glance

How to write a Flutter integration test on the real app, measure frames in profile mode, use DevTools and run it in CI on Linux with xvfb.

When an integration test is worth its cost

An integration test starts the real app, drives it the way a user would and checks that widgets, navigation, state and services work together. The official testing overview describes it as the level with the highest confidence and also the highest maintenance cost, more dependencies and the lowest speed. That is why its guidance is to have "many unit and widget tests" and "enough integration tests to cover the important use cases": no fixed percentage. Anyone quoting a 70/20/10 rule is making it up, and the only sensible proportion is the one that follows your critical flows (sign-in, payment, first launch), where a regression really costs.

Before this article you saw the lower level in widget testing and golden tests; here we reuse the product row from that chapter and put it inside an app with a list of 200 entries. A statement of method: I analysed the listings with flutter analyze (no errors, Flutter 3.44.2), but I did not run them, because an integration test requires a device or a desktop with its toolchain and I launched neither tests nor builds. The outputs are therefore deduced from the sources and the documentation.

The first test: the real app, not an isolated widget

The example app is a shop with 200 product rows, each with the + button from the previous chapter. The difference from a widget test is in the first line of the test: it calls the app's main(), not pumpWidget on a single component.

The app under test: a list of 200 products (analysed, not run)
import 'package:flutter/material.dart';

import 'product_list.dart';

void main() => runApp(const ShopApp());

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('Shop')),
        body: ListView.builder(
          key: const ValueKey('products'),
          itemCount: 200,
          itemBuilder: (context, i) => ProductTile(name: 'Product $i', priceCents: 250),
        ),
      ),
    );
  }
}

The ListView.builder builds rows only when they enter the visible window, which is the reason a 200-entry list is a good test bench for scrolling: if the cost per row is high you will see it in the frames. The products key on the list lets the test find it without depending on text.

Two integration tests: a flow and a measurement (analysed, not run)
import 'package:fa/shop_app.dart' as app;
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';

void main() {
  final binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized();

  testWidgets('two taps on the first product bring the total to 5.00 €', (tester) async {
    app.main(); // the real app, not an isolated widget
    await tester.pumpAndSettle();

    final firstPlus = find.byKey(const ValueKey('add')).first;
    await tester.tap(firstPlus);
    await tester.tap(firstPlus);
    await tester.pumpAndSettle();

    expect(find.text('Total: 5.00 €'), findsOneWidget);
  });

  testWidgets('scrolling the list: frame timings', (tester) async {
    app.main();
    await tester.pumpAndSettle();

    await binding.watchPerformance(() async {
      for (var i = 0; i < 5; i++) {
        await tester.fling(find.byKey(const ValueKey('products')), const Offset(0, -600), 3000);
        await tester.pumpAndSettle();
      }
    }, reportKey: 'scroll_products');
  });
}

The integration_test package is added to dev_dependencies as sdk: flutter together with flutter_test, and the test calls IntegrationTestWidgetsFlutterBinding.ensureInitialized() as its first statement, as the package README shows. In the first test the two taps on the same button come before a single pumpAndSettle: the taps accumulate two increments and the next frame shows them together; the check of the text "5.00 €" is therefore on the result of both. The command to launch it, according to the official guide, is flutter test integration_test/shop_test.dart on a connected device, an emulator, a desktop (-d linux) or a browser, and the same guide also lists flutter drive among the commands.

Measuring frames while you scroll

The second test does not verify a result: it measures. watchPerformance, which the integration_test source documents, observes the FrameTiming values during the action and reports them under the chosen key (the default value is performance). It waits two seconds before starting to flush old timings, so a test like this lasts a few seconds more than its body. The sibling method traceAction instead records the timeline and usually writes to the file build/integration_response_data.json when the driver is used.

A measurement makes sense only in profile mode on a real device. The official performance recipe explains that the --profile option compiles the app in profile mode and not debug "so that the result is closer to what users will experience", and that on mobile devices and emulators you must add --no-dds. An emulator on a laptop, in debug, measures the emulator.

Measuring in profile mode and opening DevTools (not run)
flutter drive \
  --driver=test_driver/integration_test.dart \
  --target=integration_test/shop_test.dart \
  --profile --no-dds
dart devtools

The first part is the recipe's command adapted to our file; dart devtools starts DevTools (in this machine's help the default port is 9100, and you can pass the service address of an already running app to connect to it). The test_driver/integration_test.dart driver is the small file the official guide asks you to create; I do not reproduce it because it is one line, but without it flutter drive does not start.

DevTools: which tab for which symptom

DevTools is a set of diagnostic tools for Dart and Flutter; the official page lists, among other things, the analysis of interface smoothness problems, the CPU profile, the network profile, memory problems and app size analysis. The test measures that a frame is slow, DevTools tells you why.

  • Slow frames while scrolling: Performance tab, to see which phase (build or paint) exceeds the budget.
  • A function that eats time: CPU Profiler tab, to trace back to the responsible method.
  • Memory grows with every screen: Memory tab, comparing two snapshots before and after the operation.
  • A slow request: Network tab, to separate the waiting time from the transfer time.

Always start from the symptom and not from the tool: if the test says 5% of frames are slow, the question is which screen and which gesture, and you pick the right tab accordingly. The per-frame budget depends on the screen's refresh rate (about 16.7 ms at 60 Hz, about 8.3 ms at 120 Hz) and is not a fixed 16 ms figure as many guides repeat. To interpret what you see in the Performance tab you need to know the rendering pipeline, covered in performance and jank.

Running them in CI

The simplest way to bring these tests into continuous integration is Linux desktop: no emulator to start. The official guide warns that on Linux you need an X server and proposes xvfb-run; without it flutter test stops with "Error waiting for a debug connection: The log reader stopped unexpectedly, or never started".

GitHub Actions workflow on Linux desktop (pattern to adapt, not run)
name: integration
on: [pull_request]
jobs:
  linux-desktop:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: subosito/flutter-action@v2
        with:
          channel: stable
      - run: sudo apt-get update && sudo apt-get install -y clang cmake ninja-build pkg-config libgtk-3-dev xvfb
      - run: flutter pub get
      # Linux needs an X server: xvfb-run starts a virtual one
      - run: xvfb-run flutter test integration_test -d linux

The workflow is a pattern based on the structure of the guide: the test command and the role of xvfb-run are documented, while the system packages and the version of the actions must be confirmed on your runner. A desktop test does not replace one on a phone, because it does not verify the behaviour of the mobile system. For real devices, the same guide points to Firebase Test Lab, and for system windows (permissions, notifications) it notes that integration_test cannot interact with the native interface and suggests the patrol package.

What you can do now

You can decide which flows deserve an integration test, write one that starts from the real app, measure frames in profile mode and link DevTools to the symptom, and run it all on Linux in CI with a virtual X server. To design code that is easier to test at every level, read feature-first architecture; to understand why a tap rebuilds some widgets and not others, Flutter internals.

Sources

Commenti

Caricamento commenti...

Sign in to comment

New articles and tools on Telegram too

The Telegram channel flags the site's new articles and tools.

Did you like this article?

Explore other content on the blog or discover my projects