mock_exceptions 패키지는 테스트 중에 모크 객체에서 예외 동작을 시뮬레이션할 수 있도록 해줍니다. 특정 메서드 호출이 가짜 또는 모크 객체에서 예외를 던지도록 할 수 있어, 실제 구현에 의존하지 않고 오류 처리 시나리오를 테스트하는 데 특히 유용합니다. 코드가 실패 상황에 어떻게 반응하는지 검증함으로써 테스트 케이스의 강건성을 보장합니다. 이 패키지는 Flutter의 테스트 생태계와 원활하게 통합되며 모든 주요 플랫폼을 지원합니다. 제어된 실패 조건이 필요한 단위 테스트 및 통합 테스트에 이상적입니다.
사용 사례
오류 처리 경로 테스트
실패한 API 응답 시뮬레이션
재시도 로직 검증
유연한 마이그레이션 보장
예외 복구 테스트
일관되지 않은 동작 모킹
주요 기능
간편한 예외 주입
모든 플러터 플랫폼을 지원합니다
Fake 클래스와의 통합
최소한의 설정 필요
유연한 예외 구성
기존 테스트 프레임워크와 호환
적합한 대상
단위 테스터
통합 테스터
내구성 있는 코드를 작성하는 개발자
TDD/BDD를 사용하는 팀
현실적인 실패 시나리오가 필요한 사용자
테스트 주도 개발 워크플로
고려 사항
모킹 개념에 대한 이해가 필요합니다
생산 사용을 위한 것이 아님
적절한 테스트 구조에 의존합니다
과도하게 사용할 경우 테스트의 복잡성을 증가시킬 수 있습니다
다른 테스트 유틸리티와 함께 사용하는 것이 가장 좋습니다
예외 시뮬레이션만 가능
원본 README
연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.
mock_exceptions
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).
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
In your Fake method/getter/setter implementation, add maybeThrowException at the beginning.
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.
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).