Repository: flutter
Issue: Testing a Future.error after first build throws exception
Labels: a: tests,framework,a: error message,has reproducible steps,P2,found in release: 2.6,team-framework,triaged-framework

Hi,

I'd like to test this code when the future return an **error**

```dart
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  late Future<http.Response> _getData;

  Future<http.Response> getData() {
    return Future.error(Error());
  }

  @override
  void initState() {
    _getData = getData();
    super.initState();
  }

  Widget build(BuildContext context) {
    return FutureBuilder(
      future: _getData,
      builder: (context, snapshot) {
        if (snapshot.connectionState != ConnectionState.done) {
          return CircularProgressIndicator();
        }

        if (snapshot.hasError) {
          return Column(
            children: [
              Text("Error"),
              OutlinedButton(
                onPressed: () {
                  setState(() {
                    _getData = getData();
                  });
                },
                child: Text("Retry"),
              )
            ],
          );
        }

        return Text(snapshot.data?.toString() ?? '???');
      },
    );
  }
}
```

This is the test 

```dart
import 'package:flutter/material.dart';
import 'package:flutter_playground/main.dart';
import 'package:flutter_test/flutter_test.dart';

void main() {
  testWidgets('basic', (WidgetTester tester) async {
    // Build our app and trigger a frame.
    await tester.pumpWidget(
      MaterialApp(home: MyHomePage()),
    );

    await tester.pump();
    await tester.tap(find.text("Retry"));
    await tester.pump();
  });
}

```
It works for the first future from first build but a exception is caught after the button tap.

```
/home/william/Documents/flutter/bin/flutter --no-color test --machine --start-paused test/test_widget.dart
Testing started at 11:25 ...

══╡ EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK ╞════════════════════════════════════════════════════
The following Error was thrown running a test:
Instance of 'Error'

When the exception was thrown, this was the stack:
#2      _MyHomePageState.getData (package:flutter_playground/main.dart:27:19)
#3      _MyHomePageState.build.<anonymous closure>.<anonymous closure>.<anonymous closure> (package:flutter_playground/main.dart:51:32)
#4      State.setState (package:flutter/src/widgets/framework.dart:1088:30)
#5      _MyHomePageState.build.<anonymous closure>.<anonymous closure> (package:flutter_playground/main.dart:50:19)
#6      _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:989:21)
#7      GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:193:24)
#8      TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:608:11)
#9      BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:296:5)
#10     BaseTapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:230:7)
#11     PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:558:9)
#12     PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:94:12)
#13     PointerRouter._dispatchEventToRoutes.<anonymous closure> (package:flutter/src/gestures/pointer_router.dart:139:9)
#14     _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:400:8)
#15     PointerRouter._dispatchEventToRoutes (package:flutter/src/gestures/pointer_router.dart:137:18)
#16     PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:123:7)
#17     GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:440:19)
#18     GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:420:22)
#19     RendererBinding.dispatchEvent (package:flutter/src/rendering/binding.dart:278:11)
#20     GestureBinding._handlePointerEventImmediately (package:flutter/src/gestures/binding.dart:374:7)
#21     GestureBinding.handlePointerEvent (package:flutter/src/gestures/binding.dart:338:5)
#22     TestWidgetsFlutterBinding.handlePointerEventForSource.<anonymous closure> (package:flutter_test/src/binding.dart:513:42)
#23     TestWidgetsFlutterBinding.withPointerEventSource (package:flutter_test/src/binding.dart:523:11)
#24     TestWidgetsFlutterBinding.handlePointerEventForSource (package:flutter_test/src/binding.dart:513:5)
#25     WidgetTester.sendEventToBinding.<anonymous closure> (package:flutter_test/src/widget_tester.dart:812:15)
#26     WidgetTester.sendEventToBinding.<anonymous closure> (package:flutter_test/src/widget_tester.dart:811:39)
#29     TestAsyncUtils.guard (package:flutter_test/src/test_async_utils.dart:71:41)
#30     WidgetTester.sendEventToBinding (package:flutter_test/src/widget_tester.dart:811:27)
#31     TestGesture.up.<anonymous closure> (package:flutter_test/src/test_pointer.dart:394:24)
#32     TestGesture.up.<anonymous closure> (package:flutter_test/src/test_pointer.dart:392:39)
#35     TestAsyncUtils.guard (package:flutter_test/src/test_async_utils.dart:71:41)
#36     TestGesture.up (package:flutter_test/src/test_pointer.dart:392:27)
#37     WidgetController.tapAt.<anonymous closure> (package:flutter_test/src/controller.dart:280:21)
#40     WidgetController.tapAt.<anonymous closure> (package:flutter_test/src/controller.dart:0:0)
#43     TestAsyncUtils.guard (package:flutter_test/src/test_async_utils.dart:71:41)
#44     WidgetController.tapAt (package:flutter_test/src/controller.dart:278:27)
#45     WidgetController.tap (package:flutter_test/src/controller.dart:273:12)
#46     main.<anonymous closure> (file:///home/william/Documents/repos/flutter_playground/test/test_widget.dart:13:18)
#49     main.<anonymous closure> (file:///home/william/Documents/repos/flutter_playground/test/test_widget.dart:0:0)
#50     testWidgets.<anonymous closure>.<anonymous closure> (package:flutter_test/src/widget_tester.dart:176:29)
#53     testWidgets.<anonymous closure>.<anonymous closure> (package:flutter_test/src/widget_tester.dart:0:0)
#54     TestWidgetsFlutterBinding._runTestBody (package:flutter_test/src/binding.dart:817:19)
#59     TestWidgetsFlutterBinding._runTest (package:flutter_test/src/binding.dart:795:14)
#60     AutomatedTestWidgetsFlutterBinding.runTest.<anonymous closure> (package:flutter_test/src/binding.dart:1226:24)
#61     FakeAsync.run.<anonymous closure>.<anonymous closure> (package:fake_async/fake_async.dart:178:54)
#66     withClock (package:clock/src/default.dart:48:10)
#67     FakeAsync.run.<anonymous closure> (package:fake_async/fake_async.dart:178:22)
#72     FakeAsync.run (package:fake_async/fake_async.dart:178:7)
#73     AutomatedTestWidgetsFlutterBinding.runTest (package:flutter_test/src/binding.dart:1223:15)
#74     testWidgets.<anonymous closure> (package:flutter_test/src/widget_tester.dart:169:24)
#75     Declarer.test.<anonymous closure>.<anonymous closure> (package:test_api/src/backend/declarer.dart:199:19)
#78     Declarer.test.<anonymous closure>.<anonymous closure> (package:test_api/src/backend/declarer.dart:0:0)
#83     Declarer.test.<anonymous closure> (package:test_api/src/backend/declarer.dart:197:13)
#84     Declarer.test.<anonymous closure> (package:test_api/src/backend/declarer.dart:180:48)
#85     Invoker._waitForOutstandingCallbacks.<anonymous closure> (package:test_api/src/backend/invoker.dart:257:15)
#86     Invoker._waitForOutstandingCallbacks.<anonymous closure> (package:test_api/src/backend/invoker.dart:254:14)
#91     Invoker._waitForOutstandingCallbacks (package:test_api/src/backend/invoker.dart:254:5)
#92     Invoker._onRun.<anonymous closure>.<anonymous closure>.<anonymous closure> (package:test_api/src/backend/invoker.dart:397:17)
#95     Invoker._onRun.<anonymous closure>.<anonymous closure>.<anonymous closure> (package:test_api/src/backend/invoker.dart:0:0)
#100    Invoker._onRun.<anonymous closure>.<anonymous closure> (package:test_api/src/backend/invoker.dart:386:9)
#101    Invoker._guardIfGuarded (package:test_api/src/backend/invoker.dart:429:15)
#102    Invoker._onRun.<anonymous closure> (package:test_api/src/backend/invoker.dart:385:7)
#109    Invoker._onRun (package:test_api/src/backend/invoker.dart:384:11)
#110    LiveTestController.run (package:test_api/src/backend/live_test_controller.dart:153:11)
#111    RemoteListener._runLiveTest.<anonymous closure> (package:test_api/src/backend/remote_listener.dart:257:16)
#116    RemoteListener._runLiveTest (package:test_api/src/backend/remote_listener.dart:256:5)
#117    RemoteListener._serializeTest.<anonymous closure> (package:test_api/src/backend/remote_listener.dart:209:7)
#135    _GuaranteeSink.add (package:stream_channel/src/guarantee_channel.dart:125:12)
#136    new _MultiChannel.<anonymous closure> (package:stream_channel/src/multi_channel.dart:159:31)
#140    CastStreamSubscription._onData (dart:_internal/async_cast.dart:85:11)
#174    new _WebSocketImpl._fromSocket.<anonymous closure> (dart:_http/websocket_impl.dart:1150:21)
#182    _WebSocketProtocolTransformer._messageFrameEnd (dart:_http/websocket_impl.dart:338:23)
#183    _WebSocketProtocolTransformer.add (dart:_http/websocket_impl.dart:232:46)
#193    _Socket._onData (dart:io-patch/socket_patch.dart:2166:41)
#202    new _RawSocket.<anonymous closure> (dart:io-patch/socket_patch.dart:1702:33)
#203    _NativeSocket.issueReadEvent.issue (dart:io-patch/socket_patch.dart:1213:14)
(elided 130 frames from dart:async, dart:async-patch, and package:stack_trace)

The test description was:
  basic
════════════════════════════════════════════════════════════════════════════════════════════════════

Test failed. See exception logs above.
The test description was: basic
```
It seems a test always fail on future exception after the initial build

(this issue was originally created on the mockito repository but the maintainer redirected me here)

```
flutter analyze                   
Analyzing flutter_playground...                                         
No issues found! (ran in 3.3s)
```

```
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, 2.5.2, on Fedora 34 (KDE Plasma) 5.14.9-200.fc34.x86_64, locale fr_FR.UTF-8)
[!] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
    ✗ cmdline-tools component is missing
      Run `path/to/sdkmanager --install "cmdline-tools;latest"`
      See https://developer.android.com/studio/command-line for more details.
    ✗ Android license status unknown.
      Run `flutter doctor --android-licenses` to accept the SDK licenses.
      See https://flutter.dev/docs/get-started/install/linux#android-setup for more details.
[✓] Chrome - develop for the web
[✓] Linux toolchain - develop for Linux desktop
[✓] Android Studio (version 2020.3)
[✓] IntelliJ IDEA Community Edition (version 2021.2)
[✓] VS Code (version 1.60.2)
[✓] Connected device (3 available)

! Doctor found issues in 1 category.
```