Repository: flutter
Issue: [flutter_test] Widget-testing a FutureBuilder fails when verifying file existence asynchronously
Labels: a: tests,framework,has reproducible steps,P2,found in release: 3.7,found in release: 3.8,team-framework,triaged-framework

<!-- Thank you for using Flutter!

     If you are looking for support, please check out our documentation
     or consider asking a question on Stack Overflow:
      * https://flutter.dev/
      * https://api.flutter.dev/
      * https://stackoverflow.com/questions/tagged/flutter?sort=frequent

     If you have found a bug or if our documentation doesn't have an answer
     to what you're looking for, then fill out the template below. Please read
     our guide to filing a bug first: https://flutter.dev/docs/resources/bug-reports
-->

## Steps to Reproduce

<!-- You must include full steps to reproduce so that we can reproduce the problem. -->

1. Run `flutter create my_app`.
2. Update the files as follows:

/lib/main.dart
```
import 'package:flutter/material.dart';
import 'package:my_app/my_widget.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Title',
      home: MyWidget(),
    );
  }
}
```
/lib/my_widget_test.dart
```
import 'dart:async';
import 'dart:io';
import 'package:path/path.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';

class MyWidget extends StatefulWidget {
  MyWidget();

  @override
  MyWidgetState createState() => MyWidgetState();
}

class MyWidgetState extends State<MyWidget> {
  Future<void> runOnCreate;

  @override
  void initState() {
    super.initState();
    runOnCreate = onCreate();
  }

  Future<void> onCreate() async {
    //await Future.delayed(Duration(milliseconds: 10));

    final filePath =
        join(dirname(Platform.script.toFilePath()), "widget_test.dart");
    final file = File(filePath);

    final fileExists = await file.exists();
    //final fileExists = file.existsSync();

    print("${file.absolute}: $fileExists");
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: runOnCreate,
      builder: (context, snapshot) {
        print("CONNECTION STATE ${snapshot.connectionState}");
        if (snapshot.connectionState == ConnectionState.done) {
          print("DONE");
          if (snapshot.hasError) {
            print(" - ERROR");
            return Text("Error while running onCreateFuture");
          }
          print(" - SUCCESS");
          return Center(
            child: SingleChildScrollView(
              child: Column(
                children: <Widget>[
                  RaisedButton(
                    onPressed: () async {},
                    child: Text("Button text"),
                  ),
                ],
              ),
            ),
          );
        } else {
          return Container();
        }
      },
    );
  }
}
```
/test/widget_test.dart
```
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';

import 'package:my_app/main.dart';
import 'package:my_app/my_widget.dart';

void main() {
  testWidgets('My widget test', (tester) async {
    final myapp = MyApp();

    await tester.runAsync(() async {
      await tester.pumpWidget(myapp);
      await tester.pumpAndSettle();
    });

    final myWidget = find.byType(MyWidget);
    expect(myWidget, findsOneWidget);

    final button = find.widgetWithText(RaisedButton, "Button text");
    expect(button, findsOneWidget);
  });
}
```
3. Run `flutter test`.

**Expected results:**

My understanding is that, when I check the existence of a file asynchronously `fileExists = await file.exists()`,  I should get the same result as if checked synchronously `fileExists = file.existsSync()`. The test should pass and have this output:    
```
File: '/Users/raluca/CMIC/Development/FlutterLab/test_widgets_futurebuilder/my_app/test/widget_test.dart': true
CONNECTION STATE ConnectionState.waiting
CONNECTION STATE ConnectionState.done
DONE
 - SUCCESS
00:02 +1: All tests passed!      
```

**Actual results:** 

The FutureBuilder's future does not finish and the test fails:


<details>
<summary>logs</summary>

```bash
00:02 +0: My widget test                                                                                                                                                                
CONNECTION STATE ConnectionState.waiting
══╡ EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK ╞════════════════════════════════════════════════════
The following TestFailure object was thrown running a test:
  Expected: exactly one matching node in the widget tree
  Actual: _AncestorFinder:<zero widgets with type "RaisedButton" which is an ancestor of text
"Button text">
   Which: means none were found but one was expected

When the exception was thrown, this was the stack:
#4      main.<anonymous closure> (file:///Users/raluca/CMIC/Development/FlutterLab/test_widgets_futurebuilder/my_app/test/widget_test.dart:20:5)
<asynchronous suspension>
#5      main.<anonymous closure> (file:///Users/raluca/CMIC/Development/FlutterLab/test_widgets_futurebuilder/my_app/test/widget_test.dart)
#6      testWidgets.<anonymous closure>.<anonymous closure> (package:flutter_test/src/widget_tester.dart:146:29)
<asynchronous suspension>
#7      testWidgets.<anonymous closure>.<anonymous closure> (package:flutter_test/src/widget_tester.dart)
#8      TestWidgetsFlutterBinding._runTestBody (package:flutter_test/src/binding.dart:784:19)
<asynchronous suspension>
#11     TestWidgetsFlutterBinding._runTest (package:flutter_test/src/binding.dart:764:14)
#12     AutomatedTestWidgetsFlutterBinding.runTest.<anonymous closure> (package:flutter_test/src/binding.dart:1173:24)
#13     FakeAsync.run.<anonymous closure>.<anonymous closure> (package:fake_async/fake_async.dart:178:54)
#18     withClock (package:clock/src/default.dart:48:10)
#19     FakeAsync.run.<anonymous closure> (package:fake_async/fake_async.dart:178:22)
#24     FakeAsync.run (package:fake_async/fake_async.dart:178:7)
#25     AutomatedTestWidgetsFlutterBinding.runTest (package:flutter_test/src/binding.dart:1170:15)
#26     testWidgets.<anonymous closure> (package:flutter_test/src/widget_tester.dart:138:24)
#27     Declarer.test.<anonymous closure>.<anonymous closure> (package:test_api/src/backend/declarer.dart:175:19)
<asynchronous suspension>
#28     Declarer.test.<anonymous closure>.<anonymous closure> (package:test_api/src/backend/declarer.dart)
#33     Declarer.test.<anonymous closure> (package:test_api/src/backend/declarer.dart:173:13)
#34     Invoker.waitForOutstandingCallbacks.<anonymous closure> (package:test_api/src/backend/invoker.dart:231:15)
#39     Invoker.waitForOutstandingCallbacks (package:test_api/src/backend/invoker.dart:228:5)
#40     Invoker._onRun.<anonymous closure>.<anonymous closure>.<anonymous closure> (package:test_api/src/backend/invoker.dart:383:17)
<asynchronous suspension>
#41     Invoker._onRun.<anonymous closure>.<anonymous closure>.<anonymous closure> (package:test_api/src/backend/invoker.dart)
#46     Invoker._onRun.<anonymous closure>.<anonymous closure> (package:test_api/src/backend/invoker.dart:370:9)
#47     Invoker._guardIfGuarded (package:test_api/src/backend/invoker.dart:415:15)
#48     Invoker._onRun.<anonymous closure> (package:test_api/src/backend/invoker.dart:369:7)
#55     Invoker._onRun (package:test_api/src/backend/invoker.dart:368:11)
#56     LiveTestController.run (package:test_api/src/backend/live_test_controller.dart:153:11)
#57     RemoteListener._runLiveTest.<anonymous closure> (package:test_api/src/remote_listener.dart:256:16)
#62     RemoteListener._runLiveTest (package:test_api/src/remote_listener.dart:255:5)
#63     RemoteListener._serializeTest.<anonymous closure> (package:test_api/src/remote_listener.dart:208:7)
#81     _GuaranteeSink.add (package:stream_channel/src/guarantee_channel.dart:125:12)
#82     new _MultiChannel.<anonymous closure> (package:stream_channel/src/multi_channel.dart:159:31)
#86     CastStreamSubscription._onData (dart:_internal/async_cast.dart:85:11)
#120    new _WebSocketImpl._fromSocket.<anonymous closure> (dart:_http/websocket_impl.dart:1145:21)
#128    _WebSocketProtocolTransformer._messageFrameEnd (dart:_http/websocket_impl.dart:338:23)
#129    _WebSocketProtocolTransformer.add (dart:_http/websocket_impl.dart:232:46)
#139    _Socket._onData (dart:io-patch/socket_patch.dart:2044:41)
#148    new _RawSocket.<anonymous closure> (dart:io-patch/socket_patch.dart:1580:33)
#149    _NativeSocket.issueReadEvent.issue (dart:io-patch/socket_patch.dart:1076:14)
(elided 111 frames from dart:async and package:stack_trace)

This was caught by the test expectation on the following line:
  file:///Users/raluca/CMIC/Development/FlutterLab/test_widgets_futurebuilder/my_app/test/widget_test.dart line 20
The test description was:
  My widget test
════════════════════════════════════════════════════════════════════════════════════════════════════
00:02 +0 -1: My widget test [E]                                                                                                                                                         
  Test failed. See exception logs above.
  The test description was: My widget test
  
00:02 +0 -1: Some tests failed.
```
</details>



<details>
  <summary></summary>

<!--
      Run your application with `flutter run --verbose` and attach all the
      log output below between the lines with the backticks. If there is an
      exception, please see if the error message includes enough information
      to explain how to solve the issue.
-->

```
```

<!--
     Run `flutter analyze` and attach any output of that command below.
     If there are any analysis errors, try resolving them before filing this issue.
-->

```
Analyzing my_app...                                                     
No issues found! (ran in 1.7s)
```

<!-- Finally, paste the output of running `flutter doctor -v` here. -->

```
[✓] Flutter (Channel stable, 1.22.6, on Mac OS X 10.15.5 19F101 darwin-x64, locale en-CA)
    • Flutter version 1.22.6 at /Users/raluca/Flutter/flutter
    • Framework revision 9b2d32b605 (11 days ago), 2021-01-22 14:36:39 -0800
    • Engine revision 2f0af37152
    • Dart version 2.10.5

[✓] Android toolchain - develop for Android devices (Android SDK version 29.0.3)
    • Android SDK at /Users/raluca/Library/Android/sdk
    • Platform android-29, build-tools 29.0.3
    • Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 1.8.0_212-release-1586-b4-5784211)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 12.3)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Xcode 12.3, Build version 12C33
    • CocoaPods version 1.9.1

[✓] Android Studio (version 3.6)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin version 45.1.1
    • Dart plugin version 192.8052
    • Java version OpenJDK Runtime Environment (build 1.8.0_212-release-1586-b4-5784211)

[✓] VS Code (version 1.52.1)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.19.0

[✓] Connected device (1 available)
    • iPad Pro (9.7-inch) (mobile) • D3BC1704-E9FD-4B76-B981-1BD5FF58D21C • ios • com.apple.CoreSimulator.SimRuntime.iOS-14-3 (simulator)

• No issues found!
```

</details>