【问题标题】:flutter. Mock api call in widget test扑。小部件测试中的模拟 api 调用
【发布时间】:2019-03-10 20:37:17
【问题描述】:

我正在尝试为应用程序中的登录屏幕创建小部件测试。 所以我想测试几件事: 1. 我可以在屏幕上找到所有需要的小部件 2.空字段验证 3.登录或密码错误的场景 4. 登录成功场景

但我坚持使用第 3 项和第 4 项。正如我在小部件测试中发现的那样,flutter 不允许 api 调用 - 所以在每种情况下响应都是 400。

我找到了一种使用 mockHtmlClient 编写测试的方法。受此主题启发https://groups.google.com/forum/#!msg/flutter-dev/AnqDqgQ6vus/8BoHfxoNBwAJ

 HttpOverrides.runZoned(() async {
  // All code inside here will use the HttpClient returned below.
  await tester.pumpWidget(buildTestableWidget(LoginScreen()));
  Finder emailField = find.byKey(new Key('email'));
  await tester.enterText(emailField, 'some@some.some');

  Finder passwordField = find.byKey(Key("password"));
  await tester.enterText(passwordField, 'some');



  // tap on the login button

  Finder loginButton = find.byKey(new Key('login'));
  await tester.tap(loginButton);

  // 'pump' the tester again. This causes the widget to rebuild
  await tester.pump();
  //sleep(const Duration(seconds:2));
  // await tester.pump();

  //find validation text on SnackBar
  expect(find.text("Invalid email or password"), findsOneWidget);

}, createHttpClient: createMockHttpClient);

我的问题是 - 我如何实现 MockHttpClient 以便我可以为 3 和 4 场景发送正确的 API 响应。我可以从这个场景的真实 api 获得 json 答案。 在我上面发布的链接的讨论中,对于 NetworkImage 的情况,有 createMockHttpClient 的实现。

【问题讨论】:

    标签: api testing dart mockito flutter


    【解决方案1】:

    我也无法使runZonedcreateHttpClient 工作。

    我用

    setUp(() {
      HttpOverrides.global = TestHttpOverrides({
        'www.example.com/dummy.png':
            dummyAvatarImageData,
        imageThumbUrl: dummyPngImageData,
      });
    });
    

    class TestHttpOverrides extends HttpOverrides {
      TestHttpOverrides(this.data);
    
      final Map<Uri, List<int>> data;
    
      @override
      HttpClient createHttpClient(SecurityContext context) =>
          createMockImageHttpClient(context, data);
    }
    

    【讨论】:

      猜你喜欢
      • 2016-06-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-24
      • 2020-12-21
      • 2017-07-27
      • 2021-12-30
      • 2018-02-21
      • 2018-08-14
      相关资源
      最近更新 更多