mockito Flutter综合试验中如何模拟http请求?

y53ybaqx  于 2022-11-08  发布在  Flutter
关注(0)|答案(3)|浏览(164)

我正在尝试使用Mockito来实现这一点,这是我的测试:

import 'package:http/http.dart' as http;
import 'package:utgard/globals.dart' as globals;
import 'package:flutter_driver/flutter_driver.dart';
import 'package:test/test.dart';
import 'package:mockito/mockito.dart';

class MockClient extends Mock implements http.Client {}

void main() {
  group('Login flow', () {

    final SerializableFinder loginContinuePasswordButton =
        find.byValueKey('login_continue_password_button');

    FlutterDriver driver;

    setUpAll(() async {
      driver = await FlutterDriver.connect();
    });

    tearDownAll(() async {
      if (driver != null) {
        //await driver.close();
      }
    });

    test('login with correct password', () async {
      final client = MockClient();

      when(client.post('http://wwww.google.com'))
          .thenAnswer((_) async => http.Response('{"title": "Test"}', 200));

      globals.httpClient = client;

      await driver.enterText('000000');
      await driver.tap(loginContinuePasswordButton);
    });
  });
}

这是我的http请求代码:

Future<Map<String, dynamic>> post({
  RequestType requestType,
  Map<String, dynamic> body,
}) async {
  final http.Response response =
      await globals.httpClient.post('http://wwww.google.com');

  print(response);

  final Map<String, dynamic> finalResponse = buildResponse(response);

  _managerErrors(finalResponse);

  return finalResponse;
}

这是全局的:

library utgard.globals;

import 'package:http/http.dart' as http;

http.Client httpClient = http.Client();

然而,我继续收到http错误,这表明http没有被mock替换。

gdx19jrr

gdx19jrr1#

我找到的解决方案是在 test_driver/app.dart 中定义mock,然后调用runApp函数:

import 'package:flutter/widgets.dart';
import 'package:flutter_driver/driver_extension.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:utgard/business/config/globals.dart';
import 'package:utgard/main.dart' as app;

class MockClient extends Mock implements http.Client {}

void main() {
  enableFlutterDriverExtension();

  final MockClient client = MockClient();
  // make your mocks here
  httpClient = client;

  runApp(app.MyApp());
}
pepwfjgg

pepwfjgg2#

而不是

when(client.post('http://wwww.google.com'))
          .thenAnswer((_) async => http.Response('{"title": "Test"}', 200));

尝试any,然后稍后Assert它

when(
          mockHttpClient.send(any),
        ).thenAnswer((_) async => http.Response('{"title": "Test"}', 200));
// ...
        final String capt = verify(client.send(captureAny)).captured;
        expect(capt, 'http://wwww.google.com');

有一个小的机会,调用参数是不完全是你嘲笑,所以去与any是安全的。

lo8azlld

lo8azlld3#

我们看不到您正在测试的代码,但它不太可能发出此请求:

client.post('http://wwww.google.com')

无论如何,使用mock json文件是一个很好的实践,并且您不希望在mock文件更改时更改请求。
我建议您使用Mocktail,而不要使用Mockito。
这样,您就可以使用any模拟任何调用:

// Simulate any GET :
mockHttpClient.get(any()))

// Simulate any POST :
mockHttpClient.post(any()))

以下是完整的解决方案:

class MockClient extends Mock implements http.Client {}
class FakeUri extends Fake implements Uri {}

void main() {

  setUp(() {
    registerFallbackValue(FakeUri()); // Required by Mocktail
  });
  tearDown(() {});

  MockHttpClient mockHttpClient = MockHttpClient();
  group('Login flow', () {
    test('login with correct password', () async {
      when(() => mockHttpClient.get(any())).thenAnswer(((_) async {
        return Response(mockWeatherResponse, 200);
      }));

    // Call the functions you need to test here

    }
  }
}

相关问题