mockito Dart中的模拟http.客户端出现异常

gwo2fgha  于 2022-11-08  发布在  其他
关注(0)|答案(2)|浏览(225)

我在测试发出http请求的类时遇到了一个问题。我想模拟客户端,这样每次客户端发出请求时,我都可以用一个模拟响应来回答。目前我的代码看起来像这样:

final fn = MockClientHandler;
  final client = MockClient(fn as Future<Response> Function(Request));

  when(client.get(url)).thenAnswer((realInvocation) async =>
    http.Response('{"userId": 1, "id": 2, "title": "mock"}', 200));

然而,当我运行测试时,我得到了以下异常:type '_FunctionType' is not a subtype of type '(Request) => Future<Response>' in type cast test/data_retrieval/sources/fitbit_test.dart 26:32 main
根据Flutter/Dart的说法,Mockito应该这样使用:

final client = MockClient();

  // Use Mockito to return a successful response when it calls the
  // provided http.Client.
  when(client.get(Uri.parse('https://jsonplaceholder.typicode.com/albums/1')))
      .thenAnswer((_) async => http.Response('{"userId": 1, "id": 2, "title":"mock"}', 200));

在这个例子中,客户端被模拟成没有参数,但是我想这已经改变了,因为MockClient的文档现在也接受参数了。我不知道为什么会发生这个异常,在互联网上也找不到任何东西,所以我想知道这里是否有人知道为什么会发生这个异常。

h5qlskok

h5qlskok1#

package:httpMockClient有点用词不当,它并不是真正的mock(当然它也与package:mockitoMock没有关系);它更像是一个 stub(或者可以说是一个伪代码):它具有旨在模拟普通X1 M4 N1 X对象实现。
注意Flutter的Mockito examples使用package:mockito创建了一个MockClient对象,但是这与package:http本身提供的MockClient类无关

final fn = MockClientHandler;
final client = MockClient(fn as Future<Response> Function(Request));

package:httpMockClient需要一个MockClientHandlerinstance 作为参数,但您试图传递的是MockClientHandlertype 本身。您需要提供一个实际的函数(同样,因为MockClient有一个实际的实现)。
换句话说,如果你想使用package:httpMockClient,那么你应该这样做:

Future<Response> requestHandler(Request request) async {
   return http.Response('{"userId": 1, "id": 2, "title": "mock"}', 200));
}

final client = MockClient(requestHandler);

或者,如果您希望使用package:mockito,则需要 * 完全 * 遵循https://flutter.dev/docs/cookbook/testing/unit/mocking并 * 生成 * 基于Mockito的MockClient类。

vjhs03f7

vjhs03f72#

这是文档的fetch_album_test.dart在更新时的样子!(测试通过)...

import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
import 'package:http/testing.dart';
import 'package:mocking/main.dart';
import 'package:mockito/annotations.dart';

// Generate a MockClient using the Mockito package.
// Create new instances of this class in each test.
@GenerateMocks([http.Client])
void main() {
  group('fetchAlbum', () {
    test('returns an Album if the http call completes successfully', () async {
      final client = MockClient((_) async =>
          http.Response('{"userId": 1, "id": 2, "title": "mock"}', 200));

      expect(await fetchAlbum(client), isA<Album>());
    });

    test('throws an exception if the http call completes with an error', () {
      final client = MockClient((_) async => http.Response('Not Found', 404));

      expect(fetchAlbum(client), throwsException);
    });
  });
}

相关问题