search
LoginSignup
1

More than 1 year has passed since last update.

posted at

updated at

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


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>が戻り値になる

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
What you can do with signing up
1