我正尝试为我的一项服务(作为TokenService)编写单元测试,该服务超出BaseService。其中BaseService是我的具有dio客户端的常见服务调用。甚至我正在使用Mock服务,它仅调用实际服务,
TokenService
import '../../src/providers/provider.dart';
import '../constants/constants.dart';
import '../models/models.dart';
import './network-call/base-service.dart';
class TokenService extends BaseService implements IsTokenService {
TokenService({this.tokenProvider});
final TokenProvider tokenProvider;
@override
Future<String> getToken() async {
final dynamic response = await serviceCall(
url: ApiName().apiName(api: ServiceName.TOKEN),
method: ApiMethod.POST,
queryParameters: {
'id': Preferences().env['id'],
'secret': Preferences().env['secret'],
'type': 'password'
});
tokenProvider.setAccessToken(Preferences.isStubData
? TokenModel.fromJson(response['data']).accessToken
: TokenModel.fromJson(response.data).accessToken);
return null;
}
}
abstract class IsTokenService {
Future<String> getToken();
}
BaseService
import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:flutter/services.dart' show rootBundle;
import '../../constants/constants.dart';
import './app-interceptors.dart';
enum ApiMethod { POST, GET }
class BaseService implements IsBaseService {
static BaseOptions options = BaseOptions(
baseUrl: Preferences().env['baseUrl'],
connectTimeout: 5000,
receiveTimeout: 120000,
);
Dio dio = Dio(options);
@override
Future<dynamic> serviceCall(
{Map<String, String> url,
Map<String, Object> data = const {},
Map<String, Object> queryParameters = const {},
ApiMethod method}) async {
dio.interceptors.add(AppInterceptors());
final Response response = await dio.request<dynamic>(
url[ApiName().apiType(ServiceType.API)],
data: data,
queryParameters: queryParameters,
options: Options(
method: _apiMethod(method),
),
);
dio.interceptors.clear();
return response;
}
static String _apiMethod(ApiMethod type) {
switch (type) {
case ApiMethod.GET:
return 'GET';
case ApiMethod.POST:
return 'POST';
default:
return 'GET';
}
}
}
abstract class IsBaseService {
Future<dynamic> serviceCall();
}
测试TokenService
import '../src/services/network-call/base-service.dart';
import '../src/services/token-service.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
class MockIsBaseService extends Mock implements IsBaseService {}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
setUp(() {});
test('Testing get Access token ', () async {
final MockIsBaseService mockIsBaseService = MockIsBaseService();
when(mockIsBaseService.serviceCall()).thenAnswer((_) async {
return false;
});
final TokenService tokenService = TokenService();
final String getToken = await tokenService.getToken();
expect(getToken, true);
});
}
请致电我的实际服务来帮助我停止操作。