Dart Add Unit Test
Testing & QA16.3K installs
What it does
Write and organize unit tests for functions, methods, and classes using `package:test`. Use when creating new logic or fixing bugs to ensure code remains correct and regression-free.
Install
npx skills add https://github.com/flutter/agent-plugins --skill dart-add-unit-testWebsite
www.skills.sh/flutter/agent-plugins/dart-add-unit-testDetails
From the skill’s SKILL.md or README, by its authors. View the original
Testing Dart and Flutter Applications
Contents
Structuring Test Files
Organize test files to mirror the lib directory structure to maintain predictability.
- Place all test code within the
testdirectory at the root of the package. - Append
_test.dartto the end of all test file names (e.g.,lib/src/utils.dartshould be tested intest/src/utils_test.dart). - If writing integration tests, place them in an
integration_testdirectory at the root of the package.
Writing Tests
Utilize package:test as the standard testing library for Dart applications.
- Import
package:test/test.dart(orpackage:flutter_test/flutter_test.dartfor Flutter). - Group related tests using the
group()function to provide shared context. - Define individual test cases using the
test()function. - Validate outcomes using the
expect()function alongside matchers (e.g.,equals(),isTrue,throwsA()). - Write asynchronous tests using standard
async/awaitsyntax. The test runner automatically waits for theFutureto complete. - Manage test setup and teardown using
setUp()andtearDown()callbacks. - If testing code that relies on dependency injection, use
package:mockitoalongsidepackage:testto generate mock objects, configure fixed scenarios, and verify interactions.
Executing Tests
Select the appropriate test runner based on the project type and test location.
- If working on a pure Dart project, execute tests using the
dart testcommand. - If working on a Flutter project, execute tests using the
flutter testcommand. - If running integration tests, explicitly specify the directory path, as the default runner ignores it:
dart test integration_testorflutter test integration_test.
Test Implementation Workflow
Follow this sequential workflow when implementing new test suites. Copy the checklist to track your progress.
Task Progress
- [ ] 1. Create the test file in the
test/directory, ensuring the_test.dartsuffix. - [ ] 2. Import
package:test/test.dartand the target library. - [ ] 3. Define a
main()function. - [ ] 4. Initialize shared resources or mocks using
setUp(). - [ ] 5. Write
test()cases grouped by functionality usinggroup(). - [ ] 6. Execute the test suite using the appropriate CLI command.
- [ ] 7. Feedback Loop: Run test -> Review stack trace for failures -> Fix implementation or assertions -> Re-run until passing.
Examples
Standard Unit Test Suite
Demonstrates grouping, setup, synchronous, and asynchronous testing.
import 'package:test/test.dart';
import 'package:my_package/calculator.dart';
void main() {
group('Calculator', () {
late Calculator calc;
setUp(() {
calc = Calculator();
});
test('adds two numbers correctly', () {
expect(calc.add(2, 3), equals(5));
});
test('handles asynchronous operations', () async {
final result = await calc.fetchRemoteValue();
expect(result, isNotNull);
expect(result, greaterThan(0));
});
});
}
Mocking with Mockito
Demonstrates configuring a mock object for dependency injection testing.
import 'package:test/test.dart';
import 'package:mockito/mockito.dart';
import 'package:mockito/annotations.dart';
import 'package:my_package/api_client.dart';
import 'package:my_package/data_service.dart';
// Generate the mock using build_runner: dart run build_runner build
@GenerateNiceMocks([MockSpec()])
import 'data_service_test.mocks.dart';
void main() {
group('DataService', () {
late MockApiClient mockApiClient;
late DataService dataService;
setUp(() {
mockApiClient = MockApiClient();
dataService = DataService(apiClient: mockApiClient);
});
test('returns parsed data on successful API call', () async {
// Configure the mock
when(mockApiClient.get('/data')).thenAnswer((_) async => '{"id": 1}');
// Execute the system under test
final result = await dataService.fetchData();
// Verify outcomes and interactions
expect(result.id, equals(1));
verify(mockApiClient.get('/data')).called(1);
});
});
}More Testing & QA skills
See allTesting & QA
Test-driven development. Use when the user wants to build features or fix bugs test-first, mentions "red-green-refactor", or wants integration tests.
1.2M installsnpx skills add https://github.com/mattpocock/skills --skill tddTesting & QA
Grill the user relentlessly about a plan, decision, or idea. Use when the user wants to stress-test their thinking, or uses any 'grill' trigger phrases.
1.1M installsnpx skills add https://github.com/mattpocock/skills --skill grillingTesting & QA
Diagnosis loop for hard bugs and performance regressions. Use when the user says "diagnose"/"debug this", or reports something broken/throwing/failing/slow.
907.2K installsnpx skills add https://github.com/mattpocock/skills --skill diagnosing-bugsTesting & QA
Set up Husky pre-commit hooks with lint-staged (Prettier), type checking, and tests in the current repo. Use when user wants to add pre-commit hooks, set up Husky, configure lint-staged, or add commit-time formatting/typechecking/testing.
535.4K installsnpx skills add https://github.com/mattpocock/skills --skill setup-pre-commit
Skills are shared by members and not reviewed by us. Read a skill’s code before you install it.