为什么在 Flutter 中将单元测试标记为异步
Why to mark unit test as async in Flutter
我是 Flutter 和 TDD 的新手,我不明白为什么以及何时将单元测试标记为 flutter 中的异步。
查看 documentation 我发现了这个代码片段:
// 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);
});
});
}
如果仔细观察,您会发现第一个测试标记为 async 而第二个则不是。这是为什么?这两个测试之间有什么不同(除了案例)所以第一个必须是 async?
谢谢 :)
当你想使用await
时,你必须将一个回调或函数一般标记为async
。
你的情况:
expect(await fetchPost(client), const TypeMatcher<Post>());
await
是必需的,因为函数执行的结果很重要。他们期望返回 Post
类型,因此,他们需要 await
.
另一种情况:
expect(fetchPost(client), throwsException);
只抛异常重要,结果无关
测试时何时用 async
标记回调
只要你需要 await
,你就用 async
标记你的回调。一般来说,我会建议始终等待测试中的功能,因为否则测试将 运行 并行,这可能会显示不需要的行为。
我是 Flutter 和 TDD 的新手,我不明白为什么以及何时将单元测试标记为 flutter 中的异步。
查看 documentation 我发现了这个代码片段:
// 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);
});
});
}
如果仔细观察,您会发现第一个测试标记为 async 而第二个则不是。这是为什么?这两个测试之间有什么不同(除了案例)所以第一个必须是 async?
谢谢 :)
当你想使用await
时,你必须将一个回调或函数一般标记为async
。
你的情况:
expect(await fetchPost(client), const TypeMatcher<Post>());
await
是必需的,因为函数执行的结果很重要。他们期望返回 Post
类型,因此,他们需要 await
.
另一种情况:
expect(fetchPost(client), throwsException);
只抛异常重要,结果无关
测试时何时用 async
标记回调
只要你需要 await
,你就用 async
标记你的回调。一般来说,我会建议始终等待测试中的功能,因为否则测试将 运行 并行,这可能会显示不需要的行为。