我想用 mockito 插件测试我的提供程序,但据我所知,标头存在问题。
当我打印时显示空(响应(
如果我从 API 中删除标头
headers: {
'X-Requested-With': 'XMLHttpRequest',
'Authorization': 'Bearer $token',
},
测试工作正常,但带有标题:
NoSuchMethodError: The getter 'statusCode' was called on null.
Receiver: null
Tried calling: statusCode
dart:core Object.noSuchMethod
package:mba/resources/providers/post_provider.dart 38:20 PostProvider.fetchPosts
===== asynchronous gap ===========================
dart:async _AsyncAwaitCompleter.completeError
package:mba/resources/providers/post_provider.dart PostProvider.fetchPosts
===== asynchronous gap ===========================
dart:async _asyncThenWrapperHelper
package:mba/resources/providers/post_provider.dart PostProvider.fetchPosts
test/resources/providers/post_provider_test.dart 46:39 main.<fn>.<fn>
供应商:
import 'package:http/http.dart' as http;
import 'package:mba/env.dart';
import 'package:mba/core/models/post_model.dart';
class PostProvider {
final http.Client client;
final String _api = API;
// Map<String, List<Post>> _postsList = Map();
PostProvider(this.client);
Future<Map<String, List<Post>>> fetchPosts(String token) async {
final response = await client.get(
'${_api}posts',
headers: {
'X-Requested-With': 'XMLHttpRequest',
'Authorization': 'Bearer $token',
},
);
print('-------------');
print(response);
print(response.statusCode);
print(response.body);
//todo: decode and mapping
if (response.statusCode == 200) {
return Map();
} else {
throw 'xxxx';
}
}
测试文件:
import 'dart:io';
import 'package:mba/resources/providers/post_provider.dart';
import 'package:mockito/mockito.dart';
import 'package:http/http.dart' as http;
import 'package:flutter_test/flutter_test.dart';
import 'package:matcher/matcher.dart';
class MockClient extends Mock implements http.Client {}
void main() {
String fixture(String name) =>
File('test/fixtures/posts/$name.json').readAsStringSync();
MockClient mockClient;
PostProvider dataSource;
setUp(() {
mockClient = MockClient();
dataSource = PostProvider(mockClient);
});
group('searchVideos', () {
test(
'returns YoutubeSearchResult when the call completes successfully',
() async {
when(
mockClient.get(
argThat(
startsWith('http://localhost:55005/api'),
),
),
).thenAnswer(
(_) async => http.Response(
fixture('posts'),
200,
headers: {'content-type': 'application/json; charset=utf-8'},
),
);
var result = await dataSource.fetchPosts('resocoder');
print(result);
},
);
});
}
Mockito将响应您的when
句子,当且仅当mockClient.get()
的所有参数都与您指定的参数匹配时。
在您的情况下,您指定了一个 URL,仅此而已。由于您的代码使用 URL 和标头,因此 mockito 将不匹配,也不会执行您的thenAnswer
。
在when
句子中,您必须指定 headers 参数以匹配您测试的代码
when(
mockClient.get(
argThat(
startsWith('http://localhost:55005/api'),
),
headers: anyNamed('headers'), // Add this line
),
).thenAnswer(...);
在这里,anyNamed('headers')
将匹配任何标头。