初心者のためのフラッターの基本(パートIX)

Flutterを使用すると、アプリケーションのさまざまな部分に対して簡単で簡単なテストを作成できます。





今日は、クラス、メソッド、および個々の関数をテストするために使用されるいくつかの単体テストを作成しようとします。





また、Mockito



偽の実装を作成できるライブラリの使用も試みます。





さて、テストを始めましょう!





私たちの計画
  • パート1- 開発の概要、最初の付録、状態の概念。





  • パート2  -pubspec.yamlファイルとコマンドラインでのflutterの使用。





  • パート3  -BottomNavigationBarとナビゲーター;





  • パート4  -MVC。この特定のパターンを最も単純なものの1つとして使用します。





  • パート5  -httpパッケージ。リポジトリクラスの作成、最初のリクエスト、投稿のリスト。





  • パート6- フォーム、テキストボックスの操作、および投稿の作成。





  • パート7- 画像の操作、グリッド形式での画像の表示、ネットワークからの画像の受信、アプリケーションへの独自の画像の追加。





  • パート8-独自のテーマを作成し、カスタムフォントとアニメーションを追加します。





  • パート9(現在の記事)-テストについて少し。





必要な依存関係を追加する

我々は2つの追加パッケージを必要mockito



build_runner



ので、それらを追加し、:





#   
#     
dev_dependencies:
  flutter_test:
    sdk: flutter
  mockito: ^5.0.10
  build_runner: ^2.0.4
      
      



これでテストを開始できます





最初のテストを書く

テストオブジェクトとして小さなクラスがありますStack







class Stack<T> {
  final stack = <T>[];
  
  void push(T t) {
    stack.add(t);
  }
  
  T? pop() {
    if (isEmpty) {
      return null;
    }
    return stack.removeLast();
  }
  
  bool get isEmpty => stack.isEmpty; 
}

      
      



注意:クラスStack



はジェネリックです。





プロジェクトのルートディレクトリにtest,



テストフォルダがあります.







その中に新しいファイルを作成しましょうstack_test.dart







import 'package:flutter_test/flutter_test.dart';
import 'package:json_placeholder_app/helpers/stack.dart';

void main() {
  //  
  group("Stack", () {
    //     
    test("Stack should be empty", () {
      // expect    
      //     
      //    ,   
      expect(Stack().isEmpty, true);
    });
    test("Stack shouldn't be empty", () {
      final stack = Stack<int>();
      stack.push(5);
      expect(stack.isEmpty, false);
    });
    test("Stack should be popped", () {
      final stack = Stack<int>();
      stack.push(5);
      expect(stack.pop(), 5);
    });
    test("Stack should be work correctly", () {
      final stack = Stack<int>();
      stack.push(1);
      stack.push(2);
      stack.push(5);
      expect(stack.pop(), 5);
      expect(stack.pop(), 2);
      expect(stack.isEmpty, false);
    });
  });
}
      
      



ものすごく単純!そうではありませんか?





実際、これはユニットと呼ばれるテストの一種です。





Flutterは以下もサポートしています。





  • ウィジェットのテスト





  • 統合テスト





この記事では、単体テストについてのみ説明します。





コマンドを使用してテストを実行してみましょう flutter test test/stack_test.dart:







成功しました!





検索後のテスト

まず、メソッドを変更しましょうfetchPosts







Future<PostList> fetchPosts({http.Client? client}) async {
  //   URL,  
  //    
  final url = Uri.parse("$SERVER/posts");
  //  GET 
  final response =  (client == null) ? await http.get(url) : await client.get(url);
  //   
  if (response.statusCode == 200) {
    //      
    // json.decode  
    return PostList.fromJson(json.decode(response.body));
  } else {
    //     
    throw Exception("failed request");
  }
}
      
      



それでは、テスト自体の作成に移りましょう。





私たちは、使用するmockito



偽の作成にhttp.Client'



Aを





post_test.dart



フォルダにファイル作成しましょうtests







import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
import 'package:json_placeholder_app/data/repository.dart';
import 'package:json_placeholder_app/models/post.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';

//    
import 'post_test.mocks.dart';

//  mockito
@GenerateMocks([http.Client])
void main() {
  //   
  final repo = Repository();
  group("fetchPosts", () {
      test('returns posts if the http call completes successfully', () async {
        //   
        final client = MockClient();

        //   
        when(client.get(Uri.parse('https://jsonplaceholder.typicode.com/posts')))
            .thenAnswer((_) async => http.Response('[{"userId": 1, "id": 2, "title": "Title", "content": "Content"}]', 200));

        //    fetchPosts
        //   
        final postList = await repo.fetchPosts(client: client);
        expect(postList, isA<PostList>());
        expect(postList.posts.length, 1);
        expect(postList.posts.first.title, "Title");
      });

      test('throws an exception if the http call completes with an error', () {
        final client = MockClient();

        //  
        when(client.get(Uri.parse('https://jsonplaceholder.typicode.com/posts')))
            .thenAnswer((_) async => http.Response('Not Found', 404));

        //   
        expect(repo.fetchPosts(client: client), throwsException);
      });
  });
}
      
      



テストを開始する前に、post_test.mocks.dart



ファイルを生成する必要があります。





flutter pub run build_runner build
      
      



その後、次のコマンドを使用してテストを実行しますflutter test test/post_test.dart







出来上がり!





結論

最も単純で最もよく知られているタイプのテストの1つであるユニットについて説明しました。





すでに述べたように、Flutterを使用すると、ウィジェットを個別にテストしたり、統合テストを使用して完全なテストを実行したりできます。





便利なリンク:





  • Githubソースコード





  • ユニットテストの概要





  • Mockitoを使用したモック依存関係





  • Flutterアプリのテスト





みんな良いコード!








All Articles