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

패키지 상세v0.8.2

mock_exceptions

특정 호출에서 예외를 발생시키는 메커니즘을 제공합니다. 이는 Fake와 함께 작업할 때 유용하며, 때때로 예외를 발생시키고 싶을 때 유용합니다.

AndroidiOSWebmacOSWindowsLinux
30일 다운로드
35.3만
좋아요
5
Pub 점수
150

패키지 설치

flutter pub add mock_exceptions

패키지 개요

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

mock_exceptions 패키지는 테스트 중에 모크 객체에서 예외 동작을 시뮬레이션할 수 있도록 해줍니다. 특정 메서드 호출이 가짜 또는 모크 객체에서 예외를 던지도록 할 수 있어, 실제 구현에 의존하지 않고 오류 처리 시나리오를 테스트하는 데 특히 유용합니다. 코드가 실패 상황에 어떻게 반응하는지 검증함으로써 테스트 케이스의 강건성을 보장합니다. 이 패키지는 Flutter의 테스트 생태계와 원활하게 통합되며 모든 주요 플랫폼을 지원합니다. 제어된 실패 조건이 필요한 단위 테스트 및 통합 테스트에 이상적입니다.

사용 사례

  • 오류 처리 경로 테스트
  • 실패한 API 응답 시뮬레이션
  • 재시도 로직 검증
  • 유연한 마이그레이션 보장
  • 예외 복구 테스트
  • 일관되지 않은 동작 모킹

주요 기능

  • 간편한 예외 주입
  • 모든 플러터 플랫폼을 지원합니다
  • Fake 클래스와의 통합
  • 최소한의 설정 필요
  • 유연한 예외 구성
  • 기존 테스트 프레임워크와 호환

적합한 대상

  • 단위 테스터
  • 통합 테스터
  • 내구성 있는 코드를 작성하는 개발자
  • TDD/BDD를 사용하는 팀
  • 현실적인 실패 시나리오가 필요한 사용자
  • 테스트 주도 개발 워크플로

고려 사항

  • 모킹 개념에 대한 이해가 필요합니다
  • 생산 사용을 위한 것이 아님
  • 적절한 테스트 구조에 의존합니다
  • 과도하게 사용할 경우 테스트의 복잡성을 증가시킬 수 있습니다
  • 다른 테스트 유틸리티와 함께 사용하는 것이 가장 좋습니다
  • 예외 시뮬레이션만 가능

원본 README

연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.

mock_exceptions

pub package Dart

Provides a mechanism to throw exceptions on certain calls. This is useful when working with a Fake and we still want to occasionally make it throw exceptions. At a glance:

final f = MyFake();
whenCalling(Invocation.method(#doSomething, null))
    .on(f)
    .thenThrow(Exception());
expect(() => f.doSomething(), throwsException);

Features

  • supports mocking exceptions for methods, getters, setters.
  • supports matching on positional parameters, named parameters and type parameters (generics).
  • supports regular matchers.
  • supports omitting parameters when matching with anything.

For exhaustive usage, see our unit tests.

Differences with Mockito

Mockito lets you mock and stub methods. That means it lets you return predefined responses and throw exceptions, but not act as closely to the real thing as a Fake. Since mock_exceptions is supposed to be used on Fakes, its API unambiguously lets you mock only exceptions.

Usage

  1. In your Fake method/getter/setter implementation, add maybeThrowException at the beginning.
  2. In your unit test, set up an expectation, then verify your expectations as usual.
Before

Your Fake method might look like this. It does some real work.

class MyFake {
  String doSomething(String input) {
    return 'it works';
  }
}

Your unit test might even check that it works.

final fake = MyFake();
expect(fake.doSomething('yes'), 'it works');
After

Your Fake method checks for possible exceptions before doing the work.

class MyFake {
  String doSomething(String input) {
    maybeThrowException(this, Invocation.method(#doSomething, [input]));
    return 'it works';
  }
}

You can now forcefully throw exceptions and test for them.

final fake = MyFake();
whenCalling(Invocation.method(#doSomething, ['fun']))
    .on(fake)
    .thenThrow(Exception());
expect(() => fake.doSomething('fun'), throwsException);

Design considerations

  • whenCalling(Invocation.method(#doSomething, [equals('fun')])).on(fake).thenThrow(Exception()); is too verbose. Why not reimplement Mockito's API so that I can write when(fake.doSomething('fun')).thenThrow(Exception())?
    • Implementing Mockito's API requires relying on the noSuchMethod trick to detect the Invocation. As of writing, Mockito's mock.dart takes 1200 lines of code while our mock_exceptions.dart takes around 80. Even if we pare Mockito's down to the minimum (excluding verifications, captures), it'd still take around 500 lines of code.
    • It also forces the Fakes to extend a pre-defined class, Mock in Mockito's case. In some projects such as Fake Cloud Firestore (example), we actually need to extend another class.
  • The Mockito API has its own downsides and gotchas. See how one should use named arguments here. Also you need to use its wrappers around the regular Matchers, such as any instead of anything, and argThat(matcher).

카테고리

의존성

의존성 목록 1 개

소스 저장소

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