Skip to content
Skills Library
Programming · Testing

dart-add-unit-test

/dart-add-unit-test

Use when writing unit tests, mocking dependencies, or validating business logic for Dart CLI and backend applications.

Repository
skills ↗
Licence
MIT
Last repository change
30.08.2026

Assessment and security

100/ 100Class: good
Format25 / 25
Frontmatter with name and description, valid name, description up to 1,024 characters, name matching the folder.
Discoverability25 / 25
Description explains when to use the skill, has a reasonable length and uses third person.
Content35 / 35
At least 150 words and at most 500 lines, headings, step lists, examples or code.
Hygiene15 / 15
No placeholders such as TODO, no Windows paths, with a licence.
Riskno signals detected in the scan
Files in this package
1
Scripts
0
HTML comments
0
URLs in SKILL.md
0
Deprecation

No signals detected. Repository changed on 30.08.2026, without references to retired models or APIs.

Licence

MIT, open: use and modify while retaining author attribution.

What it does and when to use it

Use when writing unit tests, mocking dependencies, or validating business logic for Dart CLI and backend applications.

Original author description

Use when writing unit tests, mocking dependencies, or validating business logic for Dart CLI and backend applications.

How it works

  1. Contents
  2. Unit Testing
  3. Mocking Dependencies
  4. Test Coverage
  5. Workflow: Testing Execution
Original SKILL.md headings · 105 lines, 524 words
SKILL.md preview
---
name: dart-add-unit-test
description: Use when writing unit tests, mocking dependencies, or validating business logic for Dart CLI and backend applications.
metadata:
    platforms: "dart"
    languages: "dart"
    category: "testing"
---
# Dart Testing Suite

## Contents
- [Unit Testing](#unit-testing)
- [Mocking Dependencies](#mocking-dependencies)
- [Test Coverage](#test-coverage)
- [Workflow: Testing Execution](#workflow-testing-execution)

## Unit Testing
Utilize `package:test` as the standard testing library for Dart CLI and backend applications.
* Organize test files to mirror the `lib` directory structure. Append `_test.dart` to test files.
* Group related tests using the `group()` function.
* Use `setUp()` and `tearDown()` for shared test state.
* Write pure logic inside Domain/BLoC and extract to static pure functions for 100% unit test coverage.
* Use string interpolation for test group names: `group('$ClassName', ...)`
* Structure each test using the **Arrange-Act-Assert** (Given-When-Then) convention:
  - **Arrange**: Set up mocks, create instances, prepare input data.
  - **Act**: Call the method under test.
  - **Assert**: Verify the output or side effects.
* Separate setup from verification to keep tests readable and maintainable.

## Mocking Dependencies

### mocktail vs mockito Decision

| Criteria | `mocktail` (Recommended) | `mockito` |
|---|---|---|
| **Code generation** | Not needed | Requires `build_runner` |
| **Setup speed** | Fast (extend `Mock`) | Slower (annotation + codegen) |
| **Null safety** | Full support | Full support |
| **API style** | `when(() => mock.method())` | `when(mock.method())` |
| **Best for** | Most projects, fast iteration | Large projects with complex APIs |

**Rule**: Default to `mocktail` (no codegen, faster setup). Use `mockito` only when you need `@GenerateNiceMocks` for complex APIs with many overloads.

### mocktail Setup (Recommended)
```dart
import 'package:mocktail/mocktail.dart';

// Create mock: no code generation needed
class MockUserRepository extends Mock implements UserRepository {}

void main() {
  late MockUserRepository mockRepo;

  setUp(() {
    mockRepo = MockUserRepository();
  });

  test('fetches user successfully', () {
    // Arrange
    when(() => mockRepo.getUser('1'))
        .thenAnswer((_) async => const User(id: '1', name: 'Alice'));

    // Act
    final user = await mockRepo.getUser('1');

    // Assert
    expect(user.name, 'Alice');
    verify(() => mockRepo.getUser('1')).called(1);
  });
}
```

### mockito Setup (Code-Gen)
```dart
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';

@GenerateNiceMocks([MockSpec<UserRepository>()])
import 'user_test.mocks.dart';  // Generated by: dart run build_runner build
```

### Verification APIs

| API | Purpose |
|---|---|
| `verify(() => mock.method()).called(1)` | Assert method was called exactly once |
| `verifyNever(() => mock.method())` | Assert method was never called |
| `verifyNoMoreInteractions(mock)` | Assert no unchecked interactions remain |
| `verifyInOrder([...])` | Assert methods were called in specific order |
| `reset(mock)` | Clear all stubs and interactions |

### Registering Fallback Values
For methods with custom types as parameters:
```dart
setUpAll(() {
  registerFallbackValue(const User(id: '0', name: 'fallback'));
});
```

## Test Coverage
* Target 100% logic coverage for domain models and business logic.
* Run coverage with `dart test --coverage=coverage` or `flutter test --coverage`.
* See `dart-coverage` skill for detailed LCOV/HTML report generation.

## Workflow: Testing Execution
Follow this sequential workflow when testing a Dart feature. Copy the checklist to track progress.

### Task Progress
- [ ] **Step 1: Write Unit Tests.** Focus on core business logic. Ensure files end with `_test.dart`.
- [ ] **Step 2: Generate Mocks.** Run `dart run build_runner build` to generate mocks if using Mockito.
- [ ] **Step 3: Run Tests.** Execute `dart test`.
- [ ] **Step 4: Check Coverage.** Run `dart test --coverage=coverage` and verify coverage targets are met.

Versions

RepositoryScoreLicence
This page · dhruvanbhalara/skills100MIT
dart-lang/skills100BSD-3-Clause

Database snapshot: 13.11.2026 · package version c4ea4018f16d (SHA-256 digest of the entire package)

Downloads in the last 30 days: 0 · ranking

: harmful content, incorrect descriptions or an author’s removal request.

Similar skills

  • 90dart-logic-patterns
    Use when organizing business logic, implementing algorithmic workflows, or applying Dart data structures and pattern matching.
  • 100flutter-test-strategy
    Use when deciding what to test in a Flutter/Dart codebase and at which layer — unit vs widget vs golden vs integration — and when setting coverage gates. Complements the official how-to skills (flutter-add-widget-test, flutter-add-integration-test, flutter-add-widget-preview,…
  • 100testing
    Use when writing or reviewing Flutter/Dart tests (unit, widget, golden), fixing flaky tests, adding coverage, or choosing between unit and widget tests.
  • 100write-tests
    Guide for writing unit tests. Use this when creating tests to verify Python logic.
  • 100dart-n-flutter
    Instructions for writing Dart and Flutter code following the official recommendations. Triggers on: **/*.dart
  • 100dart
    Expert Dart programming assistance covering sound null safety, async/await futures, streams, pattern matching, records, and class constructors. Use when writing Dart logic, developing Flutter mobile/web apps, or building Dart CLI applications.

Feedback and reports

Your message goes to Bartosz Sokoliński. An email address is needed only for a reply. See the privacy policy.