Testing Flutter apps翻译-使用 Mockito 模拟依赖项

1,453 阅读4分钟

翻译首页

在某些情况下,单元测试依赖的类可能从实时Web服务或数据库中获取数据。这时可能很不方便,原因如下:

  • 调用实时服务或数据库会减慢测试的执行速度。
  • 如果Web服务或数据库返回意外结果,则曾经通过的测试可能会失败。这被称为“不可靠的测试”。
  • 很难使用实时Web服务或数据库测试所有可能的成功和失败场景。

所以,与其依赖实时的web服务或者数据库,不如你“mock”这些依赖。mock允许我们模拟一个实时的web服务或者数据库并且根据情况返回特定结果。

一般来说,你可以通过创建类的替代实现来模拟依赖项。你可以自己写这些替代实现或者使用更便捷的Mockito package

下面的步骤讲解了使用Mockito package的基础操作,更多操作请查看Mockito package documentation

步骤

  1. 添加 mockito 和 test 依赖。
  2. 创建一个方法用来测试。
  3. 创建一个模拟http.Client的测试文件。
  4. 为每个条件编写测试。
  5. 运行测试。

1. 添加 mockito 和 test 依赖。

要想使用 mockito package,你首先需要添加它和 flutter_testpubspec.yaml 文件里,添加位置在dev_dependencies下面。

你也可以使用 http package,在dependencies下面添加该依赖即可。

dependencies:
  http: <newest_version>
dev_dependencies:
  test: <newest_version>
  mockito: <newest_version>

2. 创建一个方法用来测试。

在本例中,你将对从Internet方法获取数据的fetchpost函数进行单元测试。为了测试这个函数,你需要做如下2点改变:

  1. 提供一个http.Client参数给函数。这允许你根据情况提供正确的http.Client。对于Flutter和服务端项目,你可以提供http.IOClient。对于浏览器应用程序,你可以提供http.BrowserClient。对于单元测试,你可以提供模拟的http.Client。

2.使用提供的client从网络获取数据,而不是直接使用http.get方法,否则会很难模拟数据。

这个测试函数看起来应该是这样的:

Future<Post> fetchPost(http.Client client) async {
  final response =
      await client.get('https://jsonplaceholder.typicode.com/posts/1');

  if (response.statusCode == 200) {
    // If the call to the server was successful, parse the JSON
    return Post.fromJson(json.decode(response.body));
  } else {
    // If that call was not successful, throw an error.
    throw Exception('Failed to load post');
  }
}

3. 创建一个模拟http.Client的测试文件。

下一步,创建一个测试文件和一个 MockClient 类。根据单元测试介绍中的建议,在根目录的 test 文件夹下创建一个叫 fetch_post_test.dart 的文件。

这个 MockClient 类实现了 http.Client。这将允许你将 MockClient 作为参数传递到 fetchPost 函数,并且允许你在每个测试里返回不同的结果。

// 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() {
  // Tests go here
}

4. 为每个条件编写测试。

如果你思考一下 fetchPost 函数,会想到它只能返回下面的2个结果中的一个:

  1. 如果获取数据成功,会返回一个Post数据。
  2. 如果获取数据失败,会抛出一个异常。

因此,你想要测试这两个结果。你可以使用 MockClient 返回获取数据成功的测试结果,也可以返回一个获取数据失败的测试结果。

为了实现这一点,我们使用Mockito提供的when函数。

// 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), isInstanceOf<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);
    });
  });
}

5. 运行测试。

既然你现在写好了fetchPost的单元测试,那么就可以运行它了。

 dart test/fetch_post_test.dart

你也可以使用单元测试介绍里介绍过的你喜欢的编译器里运行测试

总结:

在这个例子里,你已经学会了如何使用Mockito去测试依赖web服务器或者数据库的函数或者类。这只是一个简短的 Mockito library 和模拟概念的介绍。更多信息请查看 Mockito package