문제 설명
미래 방법을 조롱하고 'Null'유형을 얻지 않는 방법은 플러터에서 'Future<>'유형의 하위 유형이 아닙니다. (How to mock a future method and not get type 'Null' is not a subtype of type 'Future<>' in flutter)
이 클래스와 이 특정 메서드를 조롱하고 싶습니다.
class FeedApiService extends ApiService {
Future<FeedResponse> fetchFeed(Map<String, String> params) async {
...
}
...
}
내 단위 테스트는 다음과 같습니다.
class FeedApiServiceMock extends Mock implements FeedApiService {}
void main() {
test('..', () {
FeedApiServiceMock feedApiServiceMock = FeedApiServiceMock();
when(feedApiServiceMock.fetchFeed({})).thenAnswer(
(_) => Future.value(FeedResponse(items: 1)),
);
expect(await feedApiServiceMock.fetchFeed({}).items, 1);
});
}
페치 피드가 올바르게 조롱되는지 확인하고 싶지만, m 이 오류가 발생함:
type 'Null' is not a subtype of type 'Future<FeedResponse>'
참조 솔루션
방법 1:
See if adding async in both the test and thenAnswer
method solves the problem.
void main() {
test('..', () async{
FeedApiServiceMock feedApiServiceMock = FeedApiServiceMock();
when(feedApiServiceMock.fetchFeed({})).thenAnswer(
(_) async=> Future.value(FeedResponse(items: 1)),
);
expect(await feedApiServiceMock.fetchFeed({}).items, 1);
});
}
(by Rares Cruceat、croxx5f)