gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 03:01:14 25 4
gpt4 key购买 nike

我是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 - 为什么在Flutter中将单元测试标记为异步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59287661/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com