为什么在 Flutter 中将单元测试标记为异步

hog*_*gar 6 dart flutter flutter-test

我是 Flutter 和 TDD 的新手,我不明白为什么以及何时在 flutter 中将单元测试标记为异步。

翻阅文档我发现了这个代码片段:

// Create a MockClient using the Mock class provided by the Mockito package.
// Create new instances of this class in each test.
class MockClient extends Mock implements http.Client {}

main() {
  group('fetchPost', () {
    test('returns a Post if the http call completes successfully', () async {
      final client = MockClient();

      // Use Mockito to return a successful response when it calls the
      // provided http.Client.
      when(client.get('https://jsonplaceholder.typicode.com/posts/1'))
          .thenAnswer((_) async => http.Response('{"title": "Test"}', 200));

      expect(await fetchPost(client), const TypeMatcher<Post>());
    });

    test('throws an exception if the http call completes with an error', () {
      final client = MockClient();

      // Use Mockito to return an unsuccessful response when it calls the
      // provided http.Client.
      when(client.get('https://jsonplaceholder.typicode.com/posts/1'))
          .thenAnswer((_) async => http.Response('Not Found', 404));

      expect(fetchPost(client), throwsException);
    });
  });
}
Run Code Online (Sandbox Code Playgroud)

如果仔细观察,您会发现第一个测试被标记为异步,而第二个则不是。这是为什么?这两个测试(除了情况之外)有什么不同,因此第一个测试必须是异步的

谢谢 :)

cre*_*not 3

当你想使用时await,你必须将回调或函数一般标记为async


在你的情况下:

expect(await fetchPost(client), const TypeMatcher<Post>());
Run Code Online (Sandbox Code Playgroud)

之所以await需要,是因为函数执行的结果很重要。他们期望Post返回一个确切的类型,因此,他们需要await.

在另一种情况下:

expect(fetchPost(client), throwsException);
Run Code Online (Sandbox Code Playgroud)

只重要的是抛出异常,但结果无关紧要。

async测试时何时标记回调

每当您需要时await,您都可以用 标记您的回调async。一般来说,我建议始终在测试中等待函数,因为否则测试将并行运行,这可能会显示出不需要的行为。