如何在使用 http.post 时进行小部件测试

We'*_*sem 2 flutter flutter-test widget-test-flutter

我正在尝试对我的项目使用小部件测试,测试工作正常,直到达到我在实际页面中使用 http 请求的程度,我认为忽略该请求

final account = await http.post(
                  'http://10.0.2.2:5000/LogIn',
                  headers: <String, String>{
                    'Content-Type': 'application/json; charset=UTF-8',
                  },
                  body: json.encode({'email': email, 'password': password}),
                );
Run Code Online (Sandbox Code Playgroud)

account.body 返回空,但在使用模拟器期间运行良好

 testWidgets("Successful Sign In", (WidgetTester tester) async {
  await tester.pumpWidget(MaterialApp(home: SignIn()));

  //1-find widgets needed
  final textfieldemail = find.byKey(Key("emailtextformfield"));
  expect(textfieldemail, findsOneWidget);
  final textfieldpassword = find.byKey(Key("passwordtextformfield"));
  expect(textfieldpassword, findsOneWidget);
  final buttonsignin = find.byKey(Key("Signin"));
  expect(buttonsignin, findsOneWidget);

  //2-execute the actual test
  await tester.enterText(textfieldemail, "Weaam.wewe91@gmail.com");
  await tester.enterText(textfieldpassword, "Weaam@91");
  await tester.tap(buttonsignin);
  await tester.pump(Duration(seconds: 5));
  //await tester.pump(Duration(seconds: 5));
  //await _navigateToAccountHome(tester);

  //3-check results
  expect(find.byType(DeliveryHome), findsOneWidget);
});
Run Code Online (Sandbox Code Playgroud)

});

我不确定我是否错过了一些东西我还是初学者

Bak*_*ker 9

testWidgets默认情况下使用模拟的 http 类,该类将始终返回 HTTP 错误 400。这可能就是您的代码在模拟器中工作但在测试中不起作用的原因。

\n

要在测试之前从 Web 服务器前缀/设置获取实际的 HTTP 响应:\nHttpOverrides.global = null;

\n

例子

\n

由dnfield(Google Flutter 团队)提供。

\n

查看完整的 github 线程

\n
import \'dart:io\';\n\nimport \'package:flutter_test/flutter_test.dart\';\nimport \'package:http/http.dart\';\n\nvoid main() {\n  setUpAll(() {\n    // \xe2\x86\x93 required to avoid HTTP error 400 mocked returns\n    HttpOverrides.global = null;\n  });\n  testWidgets(\'http\', (WidgetTester tester) async {\n    await tester.runAsync(() async {\n      final HttpClient client = HttpClient();\n      final HttpClientRequest request =\n      await client.getUrl(Uri.parse(\'https://google.com\'));\n\n      final HttpClientResponse response = await request.close();\n      print(response.statusCode);  // Should get 200\n    });\n  });\n\n  testWidgets(\'http2\', (WidgetTester tester) async {\n    await tester.runAsync(() async {\n      final result = await get(Uri.parse(\'https://google.com\'));\n      print(result.statusCode); // Should get 200\n    });\n  });\n}\n
Run Code Online (Sandbox Code Playgroud)\n