为 http.post 创建单元测试的问题



我创建了这个类来在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

我认为我的模拟方法不起作用,但我无法弄清楚问题出在哪里。当我尝试为http.post复制它 https://flutter.dev/docs/cookbook/testing/unit/mocking,我正在检查此文档.拜托,有更多经验的人可以帮助我找到问题吗?

存根期间mockClient.post(){"email": "test@test.com", "password": "Test@123"}body参数与SigninDataSourceclient.post()传递的参数不匹配。

如果检查传入的字符串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));

最新更新