You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter单元测试校验抛出指定异常不生效该如何解决?

问题根因

你当前的测试写法存在逻辑错误:你提前对_apiService.login方法执行了await操作,如果该方法确实抛出MissingDataException,await会直接触发异常中断测试执行,根本无法完成后续的类型匹配校验,所以测试必然失败。

修复方案

不要对被测试的异步方法提前执行await,直接将方法返回的Future传给expect,配合throwsA + isA做异常类型校验即可:

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

  // 核心修改:去掉await,直接传Future给expect
  expect(
    _apiService.login(email: '', password: ''),
    throwsA(isA<MissingDataException>()),
  );
});

如果你还需要同时校验异常携带的message内容是否符合预期,可以使用having方法做属性匹配:

expect(
  _apiService.login(email: '', password: ''),
  throwsA(
    isA<MissingDataException>().having(
      (e) => e.message,
      'error message',
      'Missing email or password fields',
    ),
  ),
);

注:你之前尝试的TypeMatcher<MissingDataException>()是旧版本Dart的写法,现在直接用isA<MissingDataException>()即可实现完全相同的类型匹配效果,写法更简洁。

内容的提问来源于stack exchange,提问作者Santiago Curvello

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.17 08:24:01