1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Flutter TDD Clean Architecture Course その7 - Network Info

Last updated at Posted at 2020-12-20

packageの変更

  • Android端末でのWiFi接続の挙動が保証されないため、変更
package.yaml
dependencies:
  # Swap the connectivity package for this
  data_connection_checker: ^0.3.4

NetworkInfoの実装

Test

  • resultとして Future型の値を取得して、検証している
    • awaitせず、Future同士で比較している
  • expectにてmatcherを使わず、同一インスタンスとして比較している
    • == と同じ比較になっている
network_info_test.dart
import 'package:clean_architecture_tdd_prep/core/network/network_info.dart';
import 'package:data_connection_checker/data_connection_checker.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';

class MockDataConnectionChecker extends Mock implements DataConnectionChecker {}

void main() {
  NetworkInfoImpl networkInfo;
  MockDataConnectionChecker mockDataConnectionChecker;

  setUp(() {
    mockDataConnectionChecker = MockDataConnectionChecker();
    networkInfo = NetworkInfoImpl(mockDataConnectionChecker);
  });

  group('isConnected', () {
    test(
      'should forward the call to DataConnectionChecker.hasConnection',
      () async {
        // arrange
        final tHasConnectionFuture = Future.value(true);

        when(mockDataConnectionChecker.hasConnection)
            .thenAnswer((_) => tHasConnectionFuture);
        // act
        // NOTICE: We're NOT awaiting the result
        final result = networkInfo.isConnected;
        // assert
        verify(mockDataConnectionChecker.hasConnection);
        // Utilizing Dart's default referential equality.
        // Only references to the same object are equal.
        expect(result, tHasConnectionFuture);
      },
    );
  });
}
  • 実装
network_info.dart
import 'package:data_connection_checker/data_connection_checker.dart';

abstract class NetworkInfo {
  Future<bool> get isConnected;
}

class NetworkInfoImpl implements NetworkInfo {
  final DataConnectionChecker connectionChecker;

  NetworkInfoImpl(this.connectionChecker);

  @override
  Future<bool> get isConnected => connectionChecker.hasConnection;
}

学んだこと

サードパーティーライブラリを隠蔽化するクラスを作る

  • NetworkInfo().isConnectedDataConnectionChecker().hasConnectionを読んでいるだけである
    • ライブラリの変更等があった場合、この小さいクラスの修正に留められる
      • 単一責任の原則の実践であり、ソフトウェアの変更に強い設計となっている

テストでFutureをawaitせずともassertできる

  • Future同士で比較できる
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?