首页 > 解决方案 > 需要帮助理解 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');
    }
  }

标签: fluttermockito

解决方案


推荐阅读