Learn

Test a Presenter without starting Flutter

Write a complete Dart test for adaptation, Model changes, effects and Presenter shutdown.

v1.0.0Beginnerark_mvp_test

Suppose a screen receives a task count from business logic. The Presenter turns that count into a label using the current presentation environment. We want to test that conversion, change the Model, and verify cleanup without rendering a widget or starting a UseCase.

Use ark_mvp_test when that is the boundary you need to check. For a plain function result, ordinary expect is enough. For context lookup, frame timing or widget removal, use Flutter widget tests as well.

Install the test companion

yaml
dependencies:
  ark_mvp: ^1.2.1
dev_dependencies:
  ark_mvp_test: ^1.0.0
  test: ^1.31.2

The application imports ark_mvp directly. The helper belongs in dev_dependencies; it does not add a test runner or Flutter to runtime code.

First complete test

Save this as test/count_presenter_test.dart, run dart pub get, then run dart test test/count_presenter_test.dart. This is the same complete test checked in the published English README.

dart
import 'package:ark_mvp/ark_mvp.dart';
import 'package:ark_mvp_test/ark_mvp_test.dart';
import 'package:test/test.dart';

void main() {
  test('adapt the current count for the chosen environment', () async {
    final PresenterTestDriver<int, String, String, String> driver =
        PresenterTestDriver<int, String, String, String>(
          presenter: _CountPresenter(),
          initialModel: 3,
        );
    addTearDown(driver.close);
    driver.start();

    expect(driver.buildViewState('tasks'), '3 tasks');
    expect(driver.buildViewState('задачи'), '3 задачи');
    driver.updateModel(4);
    expect(driver.buildViewState('tasks'), '4 tasks');

    await driver.close();
    await driver.observer.waitForDone();
    expect(driver.observer.effects, isEmpty);
  });
}

final class _CountPresenter extends Presenter<int, String, String, String> {
  @override
  String buildViewState(final String environment) => '$model $environment';
}

What each part proves

  1. _CountPresenter adapts the current Model and Environment. The four type parameters are Model, ViewState, ViewEffect and Environment, in that order.
  2. The driver creates a real PresenterSession and attaches listeners before start(). An initial effect cannot be missed because the test subscribed late.
  3. The first two builds use the same Model with different vocabulary. The third uses the updated Model. No new Presenter is created.
  4. addTearDown registers cleanup even if an assertion fails. Explicit close at the end also lets this test check that both output streams actually finish.

The strings keep the example small. Your feature can use immutable Model and ViewState classes and a typed effect hierarchy instead.

Effects and rebuild requests are different outputs

Keep a reference to your concrete Presenter when testing one of its actions. Call that action, then await driver.observer.waitForEffectCount(1) and inspect driver.observer.effects. The observer records an effect; it does not execute navigation, show a dialog or run any other platform work.

waitForInvalidationCount(1) waits for a request to rebuild. It does not build ViewState. Call driver.buildViewState(environment) yourself and assert its result. driver.viewStates records only those successful explicit builds.

A count means at least the requested number, including previous history. To assert an exact final sequence, await successful driver close and natural stream completion before comparing the entire list. Reaching the first count does not prove there will be no extra events.

See the complete effects and close test: it captures an effect emitted during attachment and checks that a guarded late result is rejected after shutdown.

A Model composed from several sources

The driver accepts a complete Model snapshot; it does not subscribe to business managers or synchronize them. In the composed Model example, an ordinary ModelBinding reads task and save state. The test explicitly reads the next snapshot and passes it to updateModel.

This is the same adaptation boundary whether one UseCase, several UseCases or another state manager provides the data. It is not a cross-manager transaction, and the helper does not choose an application state manager for you.

Who owns cleanup?

ObjectOwner and cleanup
Driver-created session and PresenterDriver; await driver.close()
Business objects read by a ModelBindingApplication or test; close them separately
Observer attached to an external sessionObserver owns only its two subscriptions; await observer.cancel()
External sessionIts original owner; observer cancellation does not close it

Create a standalone PresenterTestObserver<E> with the session's effects and invalidations streams before starting that session. It adds no replay. Cancellation is not natural completion, although delivered history remains readable. Histories are unmodifiable snapshots; their elements are not deep-copied.

Deadlines and errors

Every wait has an independent positive timeout, five seconds by default. Timeout ends that wait only: it does not cancel an action or make a hanging cleanup succeed. The close Future represents the real cleanup and has no hidden deadline.

PresenterTestObservationException.reason distinguishes timeout, cancelled, completedEarly and streamError. A delivered stream error retains its channel, original object and StackTrace and fails pending and future waits. By contrast, failures thrown by start, updateModel, buildViewState or close remain operation failures: assert on the method itself. Streams can finish even if cleanup fails, so waitForDone() alone does not prove successful close.

Timers use the current Dart Zone. Advance fake time explicitly in fake_async; the driver does not pump Flutter frames or execute ViewEffects.

Next steps