LoginSignup
1
1

More than 3 years have passed since last update.

Flutter TDD Clean Architecture Course その9 - Remote Data Source

Last updated at Posted at 2020-12-21

HTTP ClientのMock化

  • httpパッケージを利用する

getConcreteNumberTrivia

APIのresponse

  • 通常はplain textのResponseを受ける
  • application/jsonヘッダーを送りJSONのResponseを受ける方法は2通りある

正常系TDD

異常系

test.dart
test(
  'should throw a ServerException when the response code is 404 or other',
  () async {
    // arrange
    when(mockHttpClient.get(any, headers: anyNamed('headers'))).thenAnswer(
      (_) async => http.Response('Something went wrong', 404),
    );
    // act
    final call = dataSource.getConcreteNumberTrivia;
    // assert
    expect(() => call(tNumber), throwsA(TypeMatcher<ServerException>()));
  },
);
implementation.dart
@override
Future<NumberTriviaModel> getConcreteNumberTrivia(int number) async {
  final response = await client.get(
    'http://numbersapi.com/$number',
    headers: {'Content-Type': 'application/json'},
  );

  if (response.statusCode == 200) {
    return NumberTriviaModel.fromJson(json.decode(response.body));
  } else {
    throw ServerException();
  }
}

getRandomNumberTrivia

学んだこと

  • 前回と同じでだが、外部との境界にあるDataSourceでExceptionを投げる
    • コントロール下にあるアプリの内側では、Either<Failure, NumberTrivia>が戻り値になる
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