flutter - 需要帮助理解 Mockito 中使用的“when”函数(用于 Flutter)
问题描述
我正在学习在 Flutter 应用程序中使用 Mockito。
我的目标是进行单个单元测试,以确认所需的类(“用户”)是从模拟 API 调用返回的。
我遵循了文档和一些示例,并进行了工作测试。但是 - 我的问题是我不明白的目的when(..
?看着代码,在我看来这只是一个自我实现的预言,因为when(..
调用被硬编码为返回一个User
类对象。
所以,ermmm,这个测试不会总是通过吗?
我知道我肯定在这里误解了一些东西,希望有人为我澄清一下?(所以我可以有一个“duh”的时刻;-)
example_test.dart
class MockAuthService extends Mock implements IAuthenticationService {}
class MockClient extends Mock implements http.Client {}
void main() {
setUpAll(() {});
test('fetchUser returns a valid User object', () async {
final client = MockClient();
var mockAuthService = MockAuthService();
when(mockAuthService.fetchUser(client)).thenAnswer((_) async => User(title: "Fred"));**
(====> what exactly is this "when" line of code doing ? <====)
var result = await mockAuthService.fetchUser(client);
expect(await mockAuthService.fetchUser(client), isNotNull);
expect(result.title, "Fred");
});
}
模型
class User {
final int userId;
final int id;
final String title;
final String body;
User({this.userId, this.id, this.title, this.body});
factory User.fromJson(Map<String, dynamic> json) {
return User(
userId: json['userId'],
id: json['id'],
title: json['title'],
body: json['body'],
);
}
}
authentication_service.dart
这是我要测试的功能:
Future<User> fetchUser(http.Client client) async {
final response =
await client.get('https://jsonplaceholder.typicode.com/posts/1');
if (response.statusCode == 200) {
return User.fromJson(json.decode(response.body));
} else {
throw Exception('Failed to create a User object');
}
}
解决方案
推荐阅读
- javascript - 无法读取未定义的属性 0 - 即使使用条件渲染
- ios - 上传并保存文档后创建文件夹
- delphi - 使用 FMX 绘图功能的 Windows 预览处理程序?
- java - 如何在Android中更改私人文件根目录
- java - 如何解决 spring boot 和 Thymeleaf 上的这个错误?
- java - 得到这个异常:给定最终块没有正确填充。如果在解密期间使用了错误的密钥,则可能会出现此类问题
- flutter - 错误:无法将参数类型“void Function(bool)”分配给参数类型“void Function(bool?)”
- android - SOFT_INPUT_ADJUST_RESIZE 从 android 30 开始弃用
- visualization - 显示本体 ABox 的关系和属性值的工具
- pytorch - 将图像更改为正确形状以建模的正确方法?