简体   繁体   English

扑。 小部件测试中的模拟API调用

[英]flutter. Mock api call in widget test

I'm trying to create widget test for login screen in application. 我正在尝试为应用程序中的登录屏幕创建窗口小部件测试。 So i want to test several things: 1. That i can find all needed widgets on screen 2. Empty fields validation 3. Wrong login or password scenario 4. Successfull login scenario 所以我想测试几件事:1.我可以在屏幕上找到所有需要的小部件2.空字段验证3.错误的登录或密码方案4.成功的登录方案

But i stuck with items 3 and 4. As i found out on widget tests flutter doesn't allow api calls - so responce is 400 in every case. 但是我坚持第3项和第4项。正如我在小部件测试中发现的那样,flutter不允许api调用-因此在每种情况下响应都是400。

I found a way to write test using mockHtmlClient. 我找到了一种使用mockHtmlClient编写测试的方法。 Inspired by this topic https://groups.google.com/forum/#!msg/flutter-dev/AnqDqgQ6vus/8BoHfxoNBwAJ 受到本主题的启发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);

My question is - How can i implement MockHttpClient so i could send correct API responce for 3 and 4 scenarious. 我的问题是- 我如何实现MockHttpClient以便可以为3和4个方案发送正确的API响应。 I can get json answer from real api on this scenarious. 我可以在这种情况下从真正的api获得json答案。 There is implementation of createMockHttpClient for case of NetworkImage in the dicsussion from the linked i posted above. 在上面我发布的链接中,有针对性地针对NetworkImage的情况实现了createMockHttpClient的实现。

I also wasn't able to make runZoned with createHttpClient work. 我也无法使runZonedcreateHttpClient工作。

I use 我用

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

with

class TestHttpOverrides extends HttpOverrides {
  TestHttpOverrides(this.data);

  final Map<Uri, List<int>> data;

  @override
  HttpClient createHttpClient(SecurityContext context) =>
      createMockImageHttpClient(context, data);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM