Fixing EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK in testWidgets with FutureBuilders

I have a FutureBuilder that checks for errors and displays an error message. I wanted to write a test to check the rendering of the error, but if I passed a Future.error('some error'), the test would fail with this message:

══╡ EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK ╞════════════════════════════════════════════════════
The following message was thrown running a test:
some error

When the exception was thrown, this was the stack:

It should be simple, testing something like this:

  future: Future.error('some error'),
  builder: ...)

Yet it simply throws the error as an exception during the test.

I've tried so many combinations of try/catch, onError, catchError, expect(..., throwsException)... Eventually, this post helped me fix it. Great explanation, I'd never have guessed.

The pattern I should use is:

testWidgets('Diplays errors', (widgetTester) async {
  final Completer<MyDataType> completer = Completer();
  await widgetTester.pumpWidget(MaterialApp(
    home: Scaffold(
      body: ...
          future: completer.future,
          builder: ...)));

  // Make the future fail.
  completer.completeError('Bad SVG');
  // Wait for the render.
  await widgetTester.pumpAndSettle();

  // Check the widgets.
  expect(..., findsOneWidget);