Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/dart/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Flutter 测试颤振中是否引发了特定异常_Flutter_Dart_Testing - Fatal编程技术网

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()),
);

很有效,谢谢