[英]Problems to create a unit test for http.post
我創建了這個 class 以在 dart 中使用 http.post:
class SigninDataSource {
final http.Client client;
SigninDataSource(this.client);
Future<SignIn> signIn ({
String email = 'test@hotmail.com',
String password = 'test',
}) async {
var url = "https://test/test/signin";
var body = json.decode('{"email": "$email", "password": "$password"}');
final result = await client.post(url, body: json.encode(body), headers: {"content-type": "application/json",});
print("Result");
print(result);
if(result.statusCode == 200) {
SignIn.fromJson((result.body));
return SignIn.fromJson(result.body);
} else {
throw SignInError(json.decode(result.body)['message']);
}
}
}
我試圖為它創建一個單元測試。
class MockClient extends Mock implements http.Client {}
void main() {
String fixture(String name) => File('test/data/fixtures/$name.json').readAsStringSync();
MockClient mockClient;
SigninDataSource dataResource;
setUp((){
mockClient = MockClient();
dataResource = SigninDataSource(mockClient);
});
group('signin', () {
test(
'return SignIn whrn the service call complete succesfully',
() async {
when(
mockClient.post(
"https://test/test/signin",
body: '{"email": "test@test.com", "password": "Test@123"}',
headers: {"content-type": "application/json"}
)).thenAnswer(
(_) async => http.Response('{"status": 200}', 200));
expect(await dataResource.signIn(email: 'test@test.com', password:'Test@123'),TypeMatcher<SignIn>());
}
);
});
}
但我收到此錯誤:
Result
null
NoSuchMethodError: The getter 'statusCode' was called on null.
Receiver: null
Tried calling: statusCode
我認為我的模擬方法不起作用,但我無法弄清楚問題所在。 我正在檢查此文檔https://flutter.dev/docs/cookbook/testing/unit/mocking我試圖為 http.post 復制它。請有更多經驗的人幫我找出問題嗎?
存根期間 mockClient.post() 中的body
參數{"email": "test@test.com", "password": "Test@123"}
與mockClient.post()
中client.post()
中傳遞的SigninDataSource
不匹配。
如果您檢查在client.post()
中傳遞的字符串
從
final result = await client.post(url, body: json.encode(body), headers: {
"content-type": "application/json",
});
至
var encodedBody = json.encode(body);
final result = await client.post(url, body: encodedBody, headers: {
"content-type": "application/json",
});
encodedBody
的值為{"email":"test@test.com","password":"Test@123"}
。 注意沒有空格。
如果您想忽略傳遞的參數的值,您也可以修改您的存根,因為您只需要成功響應。 您將使用anyNamed('paramName')
。
when(mockClient.post("https://test/test/signin",
body: anyNamed('body'),
headers: anyNamed('headers')))
.thenAnswer((_) async => http.Response('{"status": 200}', 200));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.