【问题标题】:Test that a specific exception is thrown in Flutter测试 Flutter 中是否抛出了特定的异常
【发布时间】:2021-08-25 13:04:56
【问题描述】:

我有一个检查异常的测试:

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

也没有工作。

我能做什么?

提前致谢。

【问题讨论】:

    标签: flutter dart testing


    【解决方案1】:

    我终于发现,只需将 await 拉出函数即可:

    expect(
      _apiService.login(email: '', password: ''),
      throwsA(isA<MissingDataException>()),
    );
    

    【讨论】:

      【解决方案2】:

      重构这个:

      expect(
        await _apiService.login(email: '', password: ''),
        isA<MissingDataException>(),
      );
      

      到这里:

      final fn = () async => await _apiService.login(email: '', password: '');
      
      expect(
        fn,
        throwsA(isA<MissingDataException>())
      );
      

      您需要将函数引用传递给expect 以验证异常。现在,您将isA&lt;MissingDataException&gt;login() 的结果进行比较,但异常不会作为结果返回,应该进行处理。

      【讨论】:

        猜你喜欢
        • 2019-06-11
        • 2021-02-26
        • 2023-01-25
        • 1970-01-01
        • 2015-04-16
        • 1970-01-01
        • 1970-01-01
        • 2019-11-26
        • 1970-01-01
        相关资源
        最近更新 更多