LoginSignup
2
1

More than 1 year has passed since last update.

【Flutter/Dart】mocktailを使用したテストで type 'Null' is not a subtype of type 'Future<void>' のエラーが出た場合の対処法

Last updated at Posted at 2021-12-24

Flutterのテストにおいて、タイトルのエラーが出た際に手間取ったので、対処方法を備忘録として残します!

環境

-> % flutter --version
Flutter 2.5.3  channel stable  https://github.com/flutter/flutter.git
Tools  Dart 2.14.4

今回はテストライブラリであるmocktail を使用します。

 mocktail: 0.2.0

エラー内容

以下に例をあげたような、Future メソッドのテストしようとしたところ


// メソッド
 Future<void> testMethod(String id) async {
    await _testRepository.test(id);
  }

// テストコード(メソッドをモック化する)
 group('testMethod()', () {
    test(
      'should test.',
      () async {
        when(() =>_testRepository.test('test_0001'))
           .thenAnswer((_) async {});

       // expect() の処理は省略します。     
      },
    );


エラーが発生、テストが落ちるようになりました。


type 'Null' is not a subtype of type 'Future<void>'

解決方法

mocktailのドキュメントやstack overflow に記載されていた方法をいくつか試す。

最終的に、以下のようにモック化すればテストがパスするようになりました!

 group('testMethod()', () {
    test(
      'should test.',
      () async
// 引数に任意のIDを指定していたところをany()に修正
        when(() =>_testRepository.test(any()))
            .thenAnswer((_) async {});
          ),
        });
      },
    );

// ドキュメントには空文字指定の方法が紹介されていましたが、空文字だとテストが通りませんでした…

    group('testMethod()', () {
    test(
      'should test.',
      () async {
        when(() =>_testRepository.test(''))
            .thenAnswer((_) async {});
          ),
        });
      },
    );

参考

2
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
2
1