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 {});
),
});
},
);