패키지, 저장소 및 앱 카테고리 검색

패키지 상세v1.2.3

nock

Dart 및 Flutter용 HTTP 요청 모킹 라이브러리. 격리된 환경에서 애플리케이션을 테스트하세요.

AndroidiOSmacOSWindowsLinux
30일 다운로드
5.7만
좋아요
24
Pub 점수
130

패키지 설치

flutter pub add nock

패키지 개요

공개 정보를 바탕으로 생성한 선택 가이드입니다.

Nock은 실제 네트워크 호출 없이 애플리케이션의 격리된 테스트를 가능하게 하는 Dart 및 Flutter 라이브러리입니다. 개발자가 예상되는 요청 패턴과 응답을 정의할 수 있어 신뢰할 수 있고 반복 가능한 테스트 환경을 보장합니다. 유닛 테스트와 통합 테스트에 적합하며, 성공, 오류, 극단적인 경우 등 다양한 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 개

소스 저장소

이 패키지를 사용하는 프로젝트