# ChangeNotifier で更新される値の検証

以下のような class で値を検証したいとします。

```dart
class ProfileViewModel extends ChangeNotifier {
  ProfileViewModel(this._updateProfileBodyUseCase);

  final UpdateProfileBodyUseCase _updateProfileBodyUseCase;

  String _body = '';

  String get body => _body;

  void onBodyEdited(String body) {
    _updateProfileBodyUseCase.execute(body: body).then((value) {
      _body = value;
      notifyListeners();
    });
  }
}

class UpdateProfileBodyUseCase {
  Future<String> execute({required String body}) { ... }
}

```

`onBodyEdited` が `Future` であれば待って検証することができますが、この場合、`#execute` から`Future.value` を返してもそれより先に検証されてしまうため、待たなければ test が通りません。

## Recipe

これは私の知る限りでは決まった方法があるわけではないため、`Completer` での対処を一例として記載しておきます。

```dart
test('test', () async {
  when(updateProfileBodyUseCase.execute(body: anyNamed('body')))
      .thenAnswer((_) => Future.value('body'));

  final completer = Completer<void>();
  viewModel.addListener(completer.complete);

  viewModel.onBodyEdited('body');

  await completer.future;
  expect(viewModel.body, 'body');
});
```

## Result

```dart
@GenerateMocks([
  UpdateProfileBodyUseCase,
])
void main() {
  late MockUpdateProfileBodyUseCase updateProfileBodyUseCase;
  late ProfileViewModel viewModel;

  setUp(() {
    updateProfileBodyUseCase = MockUpdateProfileBodyUseCase();
    viewModel = ProfileViewModel(updateProfileBodyUseCase);
  });

  test('test', () async {
    when(updateProfileBodyUseCase.execute(body: anyNamed('body')))
        .thenAnswer((_) => Future.value('body'));

    final completer = Completer<void>();
    viewModel.addListener(completer.complete);

    viewModel.onBodyEdited('body');

    await completer.future;
    expect(viewModel.body, 'body');
  });
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://cordea.gitbook.io/flutter-test-mockito-recipes/changenotifier-verification.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
