在DART中测试异常 [英] Testing exceptions in Dart

查看:23
本文介绍了在DART中测试异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

围绕将抛出异常的代码编写测试时,DART/Mockito(或其他任何东西)如何避免抛出真正的异常? 例如,这些测试应该通过并检测抛出的异常-但DART在第一个测试中抛出真正的异常,因此只有"它接收TODO"通过。

void main() {
  test('It throws an exception', () async {
    final client = MockClient();
    when(client.get(Uri.parse('https://jsonplaceholder.typicode.com/todos/1'))).thenAnswer((_) async => http.Response('', 404));
    expect(await fetchTodo(client, 1), throwsException);
  });

  test('It receives a Todo', () async {
    final client = MockClient();
    final jsonString = '''
    {
      "id": 1,
      "userId": 1,
      "title": "test",
      "completed": false
    }
    ''';
    when(client.get(Uri.parse('https://jsonplaceholder.typicode.com/todos/2'))).thenAnswer((_) async => http.Response(jsonString, 200));
    expect(await fetchTodo(client, 2), isA<Todo>());
  });
}

和mocked get方法(基于mockito生成的代码-在我的测试文件中使用@GenerateMocks([http.Client])时得到相同的结果。

class MockClient extends Mock implements http.Client {
  Future<http.Response> get(Uri url, {Map<String, String>? headers}) {
    return super.noSuchMethod(Invocation.method(#get, [url], {#headers: headers}), returnValue: Future.value(http.Response('', 200))) as Future<http.Response>;
  }
}
class Todo {
  int id;
  int userId;
  String title;
  bool completed;

  Todo(this.id, this.userId, this.title, this.completed);
}

Future<Todo> fetchTodo(http.Client client, int id) async {
  final response = await client.get(Uri.parse('https://jsonplaceholder.typicode.com/todos/$id'));

  if(response.statusCode == 200) {
    return Todo(1, 1, 'Test', true);
  }else {
    throw Exception('Failed to fetch resource');
  }
}

测试运行报告:

00:00 +0: It throws an exception
00:00 +0 -1: It throws an exception [E]
  Exception: Failed to fetch resource
  test/test.dart 49:5  fetchTodo
  
00:00 +0 -1: It receives a Todo
00:00 +1 -1: Some tests failed.

推荐答案

您的问题在于:

expect(await fetchTodo(client, 1), throwsException);

expect()是一个普通函数,在调用函数之前会计算函数参数。(DART是一种应用顺序语言。)因此,您必须等待fetchTodo完成,然后才能调用expect()(并且expect可以尝试与throwsExceptionMatcher匹配)。

throwsA文档所述(这也适用于throwsExceptionMatcher),它必须与零参数函数或Future匹配。您不需要(也不应该)await调用fetchTodo

另外,由于您调用的是异步函数,因此无法同步检查期望值,因此您还需要使用expectLater而不是expect

await expectLater(fetchTodo(client, 1), throwsException);

这篇关于在DART中测试异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆