【问题标题】:How to make widget testing while using http.post如何在使用 http.post 时进行小部件测试
【发布时间】:2021-04-14 13:33:07
【问题描述】:

我正在尝试对我的项目使用小部件测试,并且测试工作正常,直到达到我在实际页面中使用 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}),
                );

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);
});

});

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

【问题讨论】:

    标签: flutter flutter-test widget-test-flutter


    【解决方案1】:

    testWidgets 默认使用 Mocked http 类,该类总是会返回 HTTP 错误 400。这可能是您的代码在模拟器中有效,但在测试中无效的原因。

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

    示例

    dnfield(Google Flutter 团队)提供。

    full github thread

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

    【讨论】:

      【解决方案2】:

      您不应该直接从小部件使用 http。如果是这样,那么您将 UI 与业务逻辑合并是一种不好的做法。如果两个层都没有解耦,您将无法模拟来自服务器的答案。

      一旦您的代码解耦,mockito 包将为您提供帮助。

      在测试中,你应该这样写:

      // Unstubbed methods return null.
      expect(cat.sound(), nullValue);
      
      // Stub a mock method before interacting.
      when(cat.sound()).thenReturn("Purr");
      expect(cat.sound(), "Purr");
      
      // You can call it again.
      expect(cat.sound(), "Purr");
      
      // Let's change the stub.
      when(cat.sound()).thenReturn("Meow");
      expect(cat.sound(), "Meow");
      
      // You can stub getters.
      when(cat.lives).thenReturn(9);
      expect(cat.lives, 9);
      
      // You can stub a method to throw.
      when(cat.lives).thenThrow(RangeError('Boo'));
      expect(() => cat.lives, throwsRangeError);
      
      // We can calculate a response at call time.
      var responses = ["Purr", "Meow"];
      when(cat.sound()).thenAnswer((_) => responses.removeAt(0));
      expect(cat.sound(), "Purr");
      expect(cat.sound(), "Meow");
      

      有关更多详细信息,请阅读软件包自述文件。

      【讨论】:

        猜你喜欢
        • 2018-08-16
        • 2022-01-21
        • 2021-09-22
        • 2019-02-27
        • 2019-12-27
        • 2021-04-29
        • 2021-07-11
        • 2021-11-13
        • 2022-01-12
        相关资源
        最近更新 更多