1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Dartで非同期処理をテストするときのサンプルコード

Last updated at Posted at 2024-12-21

testパッケージexpectexpectLaterで非同期処理(例:Future)を検証するときのサンプルコード

基本的な方法

import 'package:test/test.dart';

void main() {
  test('should return 1 (expect)', () {
    expect(Future.value(1), completion(1));
  });

  test('should return 1 (expectLater)', () {
    expectLater(Future.value(1), completion(1));
  });
}
  • Futureの検証はexpectでもexpectLaterでも可能
  • matcherには非同期処理用のものを指定する(completionthrowsAなど)
    • equalsactualの値それ自体(サンプルではFuture<int>)との比較をするため、非同期処理の検証で使っても期待通りの動きはしない
      • import 'package:test/test.dart';
        
        void main() {
          test('should return 1 (fails)', () {
            expect(Future.value(1), equals(1));
            // Expected: <1>
            // Actual: <Instance of 'Future<int>'>
          });
        }
        

expectexpectLaterの違うところ、同じところ

import 'package:test/test.dart';

void main() {
  test('"waiting" should be printed BEFORE "done" 1', () {
    expect(
      Future.delayed(const Duration(seconds: 5), () {
        print('done');
        return 1;
      }),
      completion(1),
    );
    print('waiting');
    // waiting
    // done
  });

  test('"waiting" should be printed BEFORE "done" 2', () async {
    expectLater(
      Future.delayed(const Duration(seconds: 5), () {
        print('done');
        return 1;
      }),
      completion(1),
    );
    print('waiting');
    // waiting
    // done
  });

  test('"waiting" should be printed AFTER "done"', () async {
    await expectLater(
      Future.delayed(const Duration(seconds: 5), () {
        print('done');
        return 1;
      }),
      completion(1),
    );
    print('waiting');
    // done
    // waiting
  });
}

  • expectexpectLaterで違うところは、非同期処理の検証完了を待てるかどうか
    • expectvoidを返すため、待つことができない
    • expectLaterは検証が終わると完了するFutureを返すため、awaitと一緒に使うことで検証完了を待つことができる
  • expectexpectLaterで同じところは、非同期処理の検証が完了するまで次のtestが実行されないこと
    • サンプルコートで言うと、"waiting" should be printed BEFORE "done" 1の中で検証がすべて完了するまで"waiting" should be printed BEFORE "done" 2の実行は始まらない
      • また、"waiting" should be printed BEFORE "done" 2の中で検証がすべて完了するまで"waiting" should be printed AFTER "done"の実行は始まらない

サンプルコードのまとめ

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?