搜索插件、代码仓与 APP 分类

插件详情v1.2.3

nock

用于 Dart 和 Flutter 的 HTTP 请求模拟库。在隔离环境中测试您的应用程序。

AndroidiOSmacOSWindowsLinux
近 30 天下载
5.7万
喜欢数
24
Pub 分数
130

安装插件

flutter pub add nock

插件介绍

基于插件公开信息、社区数据与项目使用情况整理的选型参考。

Nock 是一个用于模拟 HTTP 请求的 Dart 和 Flutter 库,可在不进行实际网络调用的情况下对应用程序进行隔离测试。它允许开发者定义预期的请求模式和响应,确保测试环境可靠且可重复。适用于单元测试和集成测试,Nock 可帮助验证您的应用如何处理各种 HTTP 场景,包括成功、错误和边界情况。通过在测试期间拦截 HTTP 请求,它提升了测试速度和可靠性。该库支持所有主要平台,包括 Android、iOS、macOS、Windows 和 Linux。

适合场景

  • 测试 API 集成
  • 模拟网络故障
  • 验证请求负载
  • 将测试与外部服务隔离
  • 模拟不同的响应场景

主要特点

  • 请求拦截
  • 灵活的响应模拟
  • 支持所有平台
  • 轻松设置,代码量最少
  • 与测试框架的集成

适合对象

  • 开发人员编写单元测试和集成测试
  • 需要一致测试环境的团队
  • 具有复杂 API 交互的项目
  • 测试驱动开发工作流程
  • CI/CD 流水线

使用建议

  • 不适用于生产环境
  • 测试文件中需要仔细设置
  • 可能需要为新的 HTTP 客户端库更新
  • 仅限 HTTP 模拟
  • 不处理HTTPS证书验证

原始 README

以下为关联源码仓库的 README 原文快照,最新内容请访问源码仓库。

Nock

HTTP requests mocking library for dart and flutter.

Nock can be used to test modules that perform HTTP requests in isolation.

Inspired by nock

Installing

Add dev dependency to your pubspec.yaml:

dev_dependencies:
  nock: ^1.2.3

Basic usage example:

import 'package:test/test.dart';
import 'package:http/http.dart' as http;
import 'package:nock/nock.dart';

void main() {
  setUpAll(() {
    nock.init();
  });

  setUp(() {
    nock.cleanAll();
  });

  test("example", () async {
    final interceptor = nock("http://localhost/api").get("/users")
      ..reply(
        200,
        "result",
      );

    final response = await http.get("http://localhost/api/users");

    expect(interceptor.isDone, true);
    expect(response.statusCode, 200);
    expect(response.body, "result");
  });
}
No mock found

if some request isn't mocked NetConnectionNotAllowed exception will be thrown:

void main() {
  test("example", () async {
    expect(
      http.get("http://localhost/api/users"),
      throwsA(TypeMatcher<NetConnectionNotAllowed>()),
    );
  });
}

API

Creating requests scope
final String baseUrl = "https://my-server.com";
final scope = nock(baseUrl);
Methods for creating interceptors
  • scope.get(dynamic url) -> Interceptor
  • scope.post(dynamic url, dynamic body) -> Interceptor
  • scope.put(dynamic url, dynamic body) -> Interceptor
  • scope.delete(dynamic url, dynamic body) -> Interceptor
  • scope.patch(dynamic url, dynamic body) -> Interceptor
  • scope.head(dynamic url, dynamic body) -> Interceptor
Using default base url

You could specify baseUrl for automatic scope usage:

void main(){
  setUpAll((){
    nock.defaultBase = "http://localhost/api";
    nock.init();
  });

  test("example", () async {
    nock.get("/users"); // create mock for GET http://localhost/api/users
  });
}
Url matching

You could use strings, regexp or any matcher from package:test:

final topicsInterceptor = nock.get("/topics")
  ..reply(200);

final usersInterceptor = nock.get(startsWith("/users"))
  ..reply(200);

final tagsInterceptor = nock.get(RegExp(r"^/tags$"))
  ..reply(200);
Specifying request headers
final interceptor = nock.get("/users")
  ..headers({
    'Session-Token': '59aff48f-369e-4781-a142-b52666cf141f',
  })
  ..reply(200);
Specifying request query string

Using query string:

final interceptor = nock.get("/users")
  ..query("ids[]=1&ids[]=2")
  ..reply(200);

Using example:

final interceptor = nock.get("/users")
  ..query({"id": 5})
  ..reply(200);

Using matchers:

final interceptor = nock.get("/users")
  ..query(startsWith("something"))
  ..reply(200);

final interceptor = nock.get("/users")
  ..query({'id': anyOf([1, 2, 3])})
  ..reply(200);

Using custom match function:

final interceptor = nock.get("/users")
  ..query((Map<String, List<String>> params) => true)
  ..reply(200);

// or

final interceptor = nock.get("/users")
  ..query((Map<String, String> params) => true)
  ..reply(200);
Specifying request body

Interceptor will parse HTTP request headers and try parse body.

Supported mime-types:

  • application/x-www-form-urlencoded
  • application/json
  • application/text
  • application/text

Using example:

final interceptor = nock.post(
    "/users",
    {
      "name": "John",
      "email": "john_doe@gmail.com",
    },
)
  ..reply(204);

Using matchers:

final interceptor = nock.post(
    "/users",
    {
      id: anyOf([1, 2, 3])
      name: any,
      email: TypedMather<String>(),
    },
)
  ..reply(204);

Using custom match function:

final interceptor = nock.post(
    "/users",
    (body) => body is Map,
)
  ..reply(204);

If you send binary data you could use custom raw match function:

final interceptor = nock.post(
    "/users",
    (List<int> body) => true,
)
  ..reply(204);
Specifying reply

application/json:

final interceptor = nock.get("/users")
  ..reply(200, [
    {
      "id": 1,
      "name": "John",
      "email": "john_doe@gmail.com",
    },
    {
      "id": 2,
      "name": "Mark",
      "email": "zuckerberg@gmail.com",
    },
  ]);

text/plain:

final interceptor = nock.get("/ping")
  ..reply(200, "pong");

Other binary data:

final interceptor = nock.get("/video")
  ..reply(200, <int>[73, 32, 97, 109, 32, 118, 105, 100, 101, 111]);
Specifying reply headers

Other binary data:

final interceptor = nock.get("/auth")
  ..reply(204, null, {
    "Session-Token": "59aff48f-369e-4781-a142-b52666cf141f",
  });
Persistent requests

To repeat responses for as long as nock is active, use .persist().

final users = nock.get("/users")
  ..persist()
  ..reply(
    200,
    "result",
  );

Note that while a persisted mock will always intercept the requests, it is considered "done" after the first interception.

Canceling pending mock:

users.cancel();
Do something after reply
final users = nock.get("/users")
  ..persist()
  ..reply(
    200,
    "result",
  )
  ..onReply(() => print("I'm done"));
Contributions Welcome!

Feel free to open PR or an issue

所属分类

依赖

依赖清单 2 项

源码仓库

使用此插件的项目