DartAdvanced 2 min read

Dart API testing: handlers, loopback HTTP and release checks

Test the HTTP contract at two boundaries and keep environment-dependent checks explicit.

On this page

An API can be tested without starting a listener for every case. Construct a Shelf Request, call the handler and inspect the Response. Add a small real loopback test to verify the adapter and network representation too.

Run the supplied project suite

Download the task REST API source and run:

dart pub get
dart analyze
dart test

The handler tests create a fresh application for each case. They verify CRUD, media types, invalid JSON, invalid UTF-8, schema rules, body limits, pagination and error sanitization. The socket test starts a listener on an OS-selected loopback port, makes real HTTP requests and closes both client and server.

Inspect a response contract

final app = createApp();
final response = await app(Request('GET', Uri.parse('http://localhost/health')));
expect(response.statusCode, 200);
expect(response.headers['content-type'], contains('application/json'));

This is a test fragment using the sample’s application factory, Shelf Request and package:test. Read the full checked-in tests before extending it so fixtures and resource cleanup remain consistent.

Test what a caller observes

After a rejected PATCH, read the task again to prove its valid state did not change. After a delete, verify both the empty 204 body and a later 404. Check that an unexpected internal exception never includes private details in the response.

Keep persistence, identity-provider and cloud tests separate. The in-memory project’s passing suite does not prove PostgreSQL, a production JWT verifier or a Linux container has been deployed correctly. Add those checks when the corresponding adapter exists.

Put checks in a release workflow

Use formatting, static analysis, deterministic tests and a target-platform build in CI. Keep credentials in the CI platform’s secret configuration, not a checked-in sample YAML. Run integration tests against disposable resources and label manual release evidence clearly.

Exercise

Add a regression test for a previously accepted invalid field. Confirm it fails before the fix and passes afterward. Then build the intended release artifact and execute one smoke request without treating a successful build as a substitute for the behavior test.

How this topic connects

Apply it next

Lesson progressMark complete after checking the example and exercise.

Find your next idea

Search lessons, code examples and projects.

Type a few words to start exploring.