Shouldly는 Dart와 Flutter용 BDD 스타일의 어설션 라이브러리로, 테스트가 실패했을 때 명확하고 설명적인 오류 메시지를 우선시합니다. 테스트 가독성과 디버깅 효율성을 향상시키기 위해 설계되었으며, 자연어처럼 읽히는 유창한 API를 제공합니다. 확장 가능하여 개발자가 특정 프로젝트 요구사항에 맞게 어설션을 사용자 정의할 수 있습니다. Android, iOS, Web, macOS, Windows, Linux 등 모든 주요 플랫폼을 지원하므로 크로스플랫폼 테스트 워크플로우에 이상적입니다.
사용 사례
읽기 쉬우면서도 유지보수 가능한 단위 테스트 작성
테스트 실패 진단 개선
테스트 기반 개발 워크플로 강화
일관된 주장과 함께 크로스 플랫폼 테스트
도메인 전용 검증을 위한 주장 로직 맞춤 설정
주요 기능
자연스럽고 인간이 읽기 쉬운 주장 구문
실패 시 자세하고 도움이 되는 오류 메시지
확장 가능한 주장 시스템
모든 플러터 플랫폼을 지원합니다
직관적인 BDD 스타일의 API
pub add를 통한 간편한 통합
적합한 대상
더 나은 테스트 피드백을 원하는 개발자
TDD 또는 BDD를 실천하는 팀
명확한 테스트 출력이 필요한 프로젝트
크로스플랫폼 플러터 애플리케이션
테스트 자동화 엔지니어
고려 사항
새로운 BDD 사용자에게는 학습 곡선이 필요할 수 있습니다
테스트 스위트의 추가 종속성
테스트 환경에 한정됨(런타임 사용은 불가)
생산 코드 어설션에 적합하지 않음
사용자 정의 주장에 대한 신중한 설정이 필요합니다
원본 README
연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.
shouldly is an assertion concept that focuses on
writing assertions as plain English sentences
and giving better error messages when the assertion fails while being simple and terse.
satisfyAllConditions will show all errors at once, not only first fail assertion.
test('should satisfy all conditions', () {
Should.satisfyAllConditions([
() => playerCharacter.nickname.should.as('nickname').not.beNullOrEmpty(),
() => playerCharacter.weapons.should.as('weapons').contain('Staff of Wonder'),
() => playerCharacter.health.should.as('health').be(100),
]);
});
Example report can be:
Expected satisfy all conditions specified, but does not.
The following errors were found ...
------------- Error 1 -------------
Expected nickname
should not be null or empty
but was
''
------------- Error 2 -------------
Expected weapons
should contain
Staff of Wonder
but was actually
[Axe, Sword]
------------- Error 3 -------------
Expected health
should be
100
but was
99
------------------------------------
Custom matchers
For existing one - just create an extension for it
extensionCustomNumAssertionsonNumericAssertions {
NumericAssertionsget beNegative {
if (subject >= 0) {
throwShouldlyTestFailureError('Number\n should be negative');
}
returnNumericAssertions(subject);
}
}
Or more exotic matchers - fot custom types
First, create a Assertions class for your custom type which extends BaseAssertions
classCustomerAssertionsextendsBaseAssertions<Customer, CustomerAssertions> {
// ...CustomerAssertionsget beMarried {
if (isReversed) {
if (subject!.isMarried) {
throwShouldlyTestFailureError('Customer should not be married');
}
} else {
if (!subject!.isMarried) {
throwShouldlyTestFailureError('Customer should be married');
}
}
returnCustomerAssertions(subject);
}
CustomerAssertionsget beMale {
if (isReversed) {
Execute.assertion
.forCondition(subject!.gender == Gender.male)
.failWith('$subjectLabel should not be male');
} else {
Execute.assertion
.forCondition(subject!.gender != Gender.male)
.failWith('$subjectLabel should be male');
}
Execute.assertion
.forCondition(subject!.gender != Gender.male)
.failWith('$subjectLabel should be male');
returnCustomerAssertions(subject);
}
// ...
}
Second, create an extension on your class which has should property with type of your custom assertions class
extensionCustomerExtensiononCustomer {
CustomerAssertionsget should => CustomerAssertions(this);
}
Third, you are ready to go use your own shouldly assertions
test('async function should throw exception', () async {
awaitShould.throwAsync(() {
Future.delayed(Duration(milliseconds: 100));
throwException('test');
});
});
test('async function should throw exact exception', () async {
awaitShould.throwAsync<CustomException>(() {
Future.delayed(Duration(milliseconds: 100));
throwCustomException('custom exception test');
});
});
test('should complete in a duration', () async {
awaitShould.completeIn(
Duration(seconds: 1),
func: () => slowFunction(
Duration(milliseconds: 900),
),
);
});
Enums
test('should not be equal', () {
seasons.spring.should.not.be(seasons.winter);
});
test('should not be type of', () {
seasons.spring.should.not.beOfType<level>();
});
test('should be assignable to `Enum`', () {
seasons.spring.should.beAssignableTo<Enum>();
});
extensionCustomerExtensiononCustomer {
CustomerAssertionsget should => CustomerAssertions(this);
}
classCustomerAssertionsextendsBaseAssertions<Customer, CustomerAssertions> {
CustomerAssertions(
Customer? subject, {
bool isReversed = false,
String? subjectLabel,
}) : super(subject, isReversed: isReversed, subjectLabel: subjectLabel);
CustomerAssertionsget beMarried {
if (isReversed) {
if (subject!.isMarried) {
throwShouldlyTestFailure('Customer should not be married');
}
} else {
if (!subject!.isMarried) {
throwShouldlyTestFailure('Customer should be married');
}
}
returnCustomerAssertions(subject);
}
CustomerAssertionsget beMale {
if (isReversed) {
if (subject!.gender == Gender.male) {
throwShouldlyTestFailure('Customer should be female');
}
} else {
if (subject!.gender != Gender.male) {
throwShouldlyTestFailure('Customer should be male');
}
}
returnCustomerAssertions(subject);
}
@overrideCustomerAssertionscopy(
Customer? subject, {
bool isReversed = false,
String? subjectLabel,
}) =>
CustomerAssertions(
subject,
isReversed: isReversed,
subjectLabel: subjectLabel,
);
}
Recommendations
You can improve the readability of the rest of your test code with given_when_then_unit_test, which enhances the test report readability as well.
Changelog
Please see the Changelog page to know what's recently changed.
Contributing
Feel free to contribute to this project.
If you find a bug or want a feature, but don't know how to fix/implement it, please fill an issue.
If you fixed a bug or implemented a new feature, please send a pull request.