Flutter 测试颤振中是否引发了特定异常
我有一个检查异常的测试:Flutter 测试颤振中是否引发了特定异常,flutter,dart,testing,Flutter,Dart,Testing,我有一个检查异常的测试: test('throws an exception if missing data', () async { final client = MockClient(); final _apiService = ApiService(client, 'test/'); when( client.post( Uri.parse('test/user/auth_user'), headers: { 'Content-
test('throws an exception if missing data', () async {
final client = MockClient();
final _apiService = ApiService(client, 'test/');
when(
client.post(
Uri.parse('test/user/auth_user'),
headers: {
'Content-Type': 'application/json',
},
body: json.encode({"email": '', "password": ''}),
),
).thenAnswer(
(_) async => http.Response(
'{"status": 400,"data": {"message": "Missing email or password fields"}}',
400,
),
);
expect(
await _apiService.login(email: '', password: ''),
isA<MissingDataException>(),
);
});
class MissingDataException implements Exception {
String message;
MissingDataException(this.message);
}
我试过了
throwsException
throwsA(TypeMatcher<MissingDataException>())
但没有起作用
我也试过了
throwsException
throwsA(TypeMatcher<MissingDataException>())
throwsA(TypeMatcher())
而且也不起作用
我能做什么
提前感谢。重构此:
expect(
await _apiService.login(email: '', password: ''),
isA<MissingDataException>(),
);
expect(
等待服务。登录(电子邮件:“”,密码:“”),
isA(),
);
为此:
final fn = () async => await _apiService.login(email: '', password: '');
expect(
fn,
throwsA(isA<MissingDataException>())
);
final fn=()async=>wait _apiService.login(电子邮件:“”,密码:“”);
期待(
fn,
throwsA(isA())
);
您需要将函数引用传递给
expect
,以验证异常。现在,您正在将isA
与login()
的结果进行比较,但是异常不会作为结果返回,它应该得到处理。我最终发现,将等待从函数中拉出就行了:
expect(
_apiService.login(email: '', password: ''),
throwsA(isA<MissingDataException>()),
);
expect(
_apiService.login(电子邮件:“”,密码:“”),
通过a(isA()),
);
很有效,谢谢