void main() {
late ApiManager apiManager;
late MockHTTPClient mockHTTPClient;
setUp(() {
mockHTTPClient = MockHTTPClient();
apiManager = ApiManager(mockHTTPClient);
});
test(
'given UserRepository class when getUser function is called and status code is 200 then a usermodel should be returned',
() async {
// Arrange
const mockResponse = '{"status": "200"}';
String url = "url";
when(() {
return mockHTTPClient.post(Uri.parse(url));
}).thenAnswer((invocation) => Future.delayed(Durations.short2,() => Response(mockResponse, 200),), );
// Act
final user = await apiManager.userLoginApi();
// Assert
expect(isuserExist, isA<Data()>());
},
);
Future<Data> userLoginApi({String? email, String? password}) async {
final response = await client.post(
Uri.parse('url'),
);
if (response.statusCode == 200) {
Map<String, String> body = {
"email": email.toString(),
"password": password.toString()
};
return Data.fromJson(body);
}
throw Exception('Some Error Occurred');
}
收到此错误“类型‘Null’不是类型‘Future’的子类型..另外,我应该在正文中传递什么。这是一个用户登录 api,其中包括电子邮件和通行证。由于它是一个测试用例,我无法通过用户凭据。
尝试改变这些:
when(() => mockHTTPClient.post(Uri.parse(url)))
.thenAnswer((_) async => Response(mockResponse, 200));
// Act
final user = await apiManager.userLoginApi(email: '[email protected]', password: 'test');
//pass mock email and password here to the userLoginApi method.
还有:
Future<Data> userLoginApi({String? email, String? password}) async {
final response = await client.post(
Uri.parse('url'),
body: {
"email": email,
"password": password,
},
);
if (response.statusCode == 200) {
Map<String, dynamic> body = json.decode(response.body);
return Data.fromJson(body); // Adjust this according to your Data model
}
throw Exception('Some Error Occurred');
}
让我们看看结果。
如果有帮助请告诉我。