Flutterexperts

Crafting Next-Gen Apps with Flutter Power
Flutter Testing: Let’s Observe

Flutter automated testing enables you to achieve higher responsiveness in your app because it helps to find bugs and other issues occurring in your app. It is also important in other perspectives like credibility as a developer.

Here comes a question which may come to your mind:

How can you know if your app is working or not if you have changed or added any features? And the answer is by writing test cases. So let’s understand how to do it.

We have 3 different testing features available

  1. Unit Test
  2. Widget Test
  3. Integration Test

Unit Tests

A unit test can be understood by its name, in the Unit test we test small parts of our code like single function, method or a class and it is very handy to do. It can be implemented by importing test package and if you want additional utilities for test flutter_test can be used.

Steps to Implement Unit Testing

  1. Add the test or flutter_test dependency.
  2. Create a test file.
  3. Create a class to test.
  4. Write a test for our class.
  5. Combine multiple tests in a group.
  6. Run the tests.

Till now we have understood how to import dependency so and let’s understand about the project structure

counter_app/
lib/testing_class.dart
test/
unit_test.dart

Now in your project, you can see that there is already a test folder in which we will create our own class for testing,

Let’s create a file testing_class.dart in which we will be multiplying two digits

Now write a class unit_test.dart in the test folder, where we will write this set of code, in this file there is a main() function and inside this function, we will write code for testing, as you can see in the “test” method object of testing class has been created and with the help of reference variable method of the testing class has been called and we are expecting the output value which should be the exact result.

And to test this code we will run the command(given below) in the terminal and observe the output of this.

flutter test test/widget_test.dart

Now let us understand the testing with the help of Mockito

Mockito is used to mock interfaces so that a dummy functionality can be added to a mock interface that can be used in unit testing.

Here we are going to understand how can we implement it.

Let’s understand it step by step

Create a simple project then delete the sample code from the main.dart file. then fix all the errors of class.

import 'package:flutter/material.dart';
import 'package:flutter_test_demo/home_page.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: HomePage(),
);
}
}

Now we are going to test our HTTP request and for this, we are using JSONPlaceholder to find the API link then we create a model class by using the response. you can also create it by using different JSON to dart converter sites.

// To parse this JSON data, do
//
// final userInfoModel = userInfoModelFromJson(jsonString);
import 'dart:convert';
UserInfoModel userInfoModelFromJson(String str) => UserInfoModel.fromJson(json.decode(str));
String userInfoModelToJson(UserInfoModel data) => json.encode(data.toJson());
class UserInfoModel {
int userId;
int id;
String title;
String body;
  UserInfoModel({
this.userId,
this.id,
this.title,
this.body,
});
  factory UserInfoModel.fromJson(Map<String, dynamic> json) => UserInfoModel(
userId: json["userId"],
id: json["id"],
title: json["title"],
body: json["body"],
);
  Map<String, dynamic> toJson() => {
"userId": userId,
"id": id,
"title": title,
"body": body,
};
}

Now we have a model class, after this, we need to make a separate class to make requests and get responses and for this, we would implement the most popular technique HTTP in api_provider class.

import 'package:flutter_test_demo/src/models/user_info_model.dart';
import 'package:http/http.dart' show Client;
import 'dart:convert';
class ApiProvider {
Client client = Client();
fetchData() async {
final response = await client.get("https://jsonplaceholder.typicode.com/posts/1");
UserInfoModel userInfoModel = UserInfoModel.fromJson(json.decode(response.body));
return userInfoModel;
}
}

Now its time to create a test class for testing, so we would be creating a file in the Test folder. when you will open this folder you will get an auto-generated file but we will delete this and create our own you can give any name to the file but remember one thing your file name should contain “_test” like api_provider_test.dart because if you don’t write then flutter would not be able to find it as a test file.

Now you need to import a few Packages to complete all the tests.

import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart';
import 'package:http/testing.dart';
import 'dart:convert';

Here HTTP package is used to use tools to mock HTTP requests and the flutter_test provides methods for testing.

Now it’s time to create a method for tests in api_provider_test.dart

import 'package:flutter_test/flutter_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart';
import 'package:http/testing.dart';
import 'dart:convert';
import 'package:flutter_test_demo/src/resources/api_provider.dart';
void main(){
test("Testing the network call", () async{
//setup the test
final apiProvider = ApiProvider();
apiProvider.client = MockClient((request) async {
final mapJson = {'id':1};
return Response(json.encode(mapJson),200);
});
final item = await apiProvider.fetchData();
expect(item.id, 1);
});
}

Here in the main() function we write the test method in which first we give a description of our test then we create the object of that api_provider class and by using its reference variable we will change the client() object into MockClient() actually MockClient is a package provided by ‘package:http/testing.dart’ which imitates an HTTP request instead of real request to the server as you can see in the above code.

In HTTP calls we make requests and get responses and we have already defined requests here.

apiProvider.client = MockClient((request) { });

And then we create response objects in this MockClient function

final mapJson = {'id':1};
return Response(json.encode(mapJson),200);

Here you can see the response object is returning the JSON object which is the body of the response and the second object is status code which is the success code of the response then we call the fetchData() which returns UserInfoModel object contains the Key ‘id’ and value “1” or not. Then in the expect method which is provided by test.dart package will compare the result we are expecting from fetchData() method.

Now let’s check whether the test cases are passing or not by running this command in your terminal.

flutter test test/api_provider_test.dart

Here api_provider_test.dart is your class name which you created for testing if your test cases pass the test you will get this response.

So this was all about unit testing in Flutter. Stay tuned for more articles related to other testing types.

Thanks for reading this article.

If you find it interesting Please Clap! and if you found anything wrong please let me know I would appreciate it for your contribution.

Connect with me on GitHub repositories.


Feel free to connect with us
And read more articles from FlutterDevs.com

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, and Twitter for any flutter related queries.

Leave comment

Your email address will not be published. Required fields are marked with *.