翻译首页web
在某些状况下,单元测试依赖的类可能从实时Web服务或数据库中获取数据。这时可能很不方便,缘由以下:数据库
因此,与其依赖实时的web服务或者数据库,不如你“mock”这些依赖。mock容许咱们模拟一个实时的web服务或者数据库而且根据状况返回特定结果。json
通常来讲,你能够经过建立类的替代实现来模拟依赖项。你能够本身写这些替代实现或者使用更便捷的Mockito package。浏览器
下面的步骤讲解了使用Mockito package
的基础操做,更多操做请查看Mockito package documentation。bash
mockito
和 test
依赖。http.Client
的测试文件。mockito
和 test
依赖。要想使用 mockito package
,你首先须要添加它和 flutter_test
到 pubspec.yaml
文件里,添加位置在dev_dependencies下面。服务器
你也可使用 http package
,在dependencies下面添加该依赖便可。网络
dependencies:
http: <newest_version>
dev_dependencies:
test: <newest_version>
mockito: <newest_version>
复制代码
在本例中,你将对从Internet方法获取数据的fetchpost函数进行单元测试。为了测试这个函数,你须要作以下2点改变:async
2.使用提供的client从网络获取数据,而不是直接使用http.get方法,不然会很难模拟数据。ide
这个测试函数看起来应该是这样的:函数
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');
}
}
复制代码
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
}
复制代码
若是你思考一下 fetchPost
函数,会想到它只能返回下面的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);
});
});
}
复制代码
既然你如今写好了fetchPost
的单元测试,那么就能够运行它了。
dart test/fetch_post_test.dart
复制代码
你也可使用单元测试介绍里介绍过的你喜欢的编译器里运行测试
在这个例子里,你已经学会了如何使用Mockito
去测试依赖web服务器或者数据库的函数或者类。这只是一个简短的 Mockito library
和模拟概念的介绍。更多信息请查看 Mockito package。