Unit Testing In Dio Dart Package

Dineth Prabashwara Benthotage
6 min readFeb 3, 2020

Introduction

When we are building large mobile applications, Unit testing is very essential to test our application. In TDD(Test Driven Development) process unit testing holds a major role in our development process. It reduces Developer Stress. When you are coding in flutter You don’t know even what are the errors in Your code until the Debugging process. But using the unit testing You can identify errors for a particular part in your code at run time. Not only Unit testing but also Integration testing as important as the Unit Testing Because In unit testing we are testing a specific unit of our code. But in Integration testing we can test whole part or module sometimes.I’m not going to explain more about Integrating testing because my topic is Unit Testing in Flutter.😂😂😂 In software engineering, these are the testing processes for any application.

Software Testing Types.

Ok, Let’s move to Our main topic. Dio,🤔 Why are we using this? It has 100% popularity more than any other HTTP packages in the dart. In my flutter experience, I know that Dio provides more functionality such as canceling network requests, lock requests, Global network request configuration, etc. It is very powerful. You can go to the pub.dev and see more about Dio and Its Syntax. I think as flutter developers You heard about the Dio.😁

Ok. First of all, I decided on how to implement the Dio. My app I needed only one Dio object for the whole app. So I created one dio object using The flutter get_it package. We can use get it to package for singleton creations with more advantages. You can see those advantages on the above page. So how do we create dio object using that package?🤔

final singleton=GetIt.instance;Future<void> _initialization(){ singleton.registerLazySingleton<ApiHelper>(
() => ApiHelper(dio: singleton()),
);
singleton.registerLazySingleton(() => Dio());
}

First I created Get It instance to create all our singleton objects. After that, I created our network layer class called ApiHelper to create network requests. All my app network requests for the API, come through this Apihelper object. Also, I passed above singleton Dio object to that ApiHelper object. That will reduce the creation of multiple Dio objects which are created for each network request. Now I have singleton ApiHelper and Dio instances. You may have a question that which time this _initialization function hits. You can add anywhere in your application before the API calls. I have used it in my main.dart.

After that, I implemented my ApiHelper class for the network layer in the app.

At first, I created dio instance to create the dio object. I created two constructors because Sometimes I have to create other network configurations before creating dio object inside the default constructor. So I created APIHelper.test constructor for testing purposes only. That type constructors are called named constructors in the dart.
According to the dio documentation, We can add interceptors, options as we wish.

dio
..options
.headers
.addAll({'parameter':'parameter'})
..interceptors.add(logInterceptor)
..options.baseUrl = NetworkConfig.getNetworkUrl();

Once the dart object was created “..” is used to take multiple operations in one object. Here in options, if you like to add headers add header corresponding parameters inside addAll function. If you like to add custom interceptors you can add also. We can provide the base URL as well. I used another method to get the base URL because all App constants are located in one file. Otherwise, It will be difficult to maintain your app scalability.

There are Custom get method and post methods in this code. Using Dio you can understand both custom methods. In my custom methods, You can see error handling in the dart. We have to handle Dio errors sometimes. That’s why here we used error handling methods when sending network requests here. We running the application we have to know about those errors that’s why I created those print methods to print the error.

final response = await dio.get(url);                             final String res = json.encode(response.data);

In this part, we can get the response using the GET HTTP method in Dio.The response. You will be confused because of why I encode my response again here. I needed to print the response as a map. So That’s why I encoded the response again here. The other part is for error handling in dio. You can try your error handling methods. My custom post method as the same as get method but It has been included body for the request.

How to Do Unit Tesing for above class?

Ok. For Unit Testing First, you have to know what are the main methods you have to test first. But in TDD(Test Driven Development) process first test cases are created before the coding. Coding is done through the test cases. But usually, we consider unit testing after the coding. Ok, Let’s create test cases for our ApiHelper class.

First, look into your pubspec.yaml file under dev dependencies. There is a default flutter test package. It is for unit testing and Integration testing. We are going to create test cases using that package. Also, we need mockito:⁴.1.1 for mock dio requests. Simply what is mocking? .It will act as a true response. In the real world, we can see those persons.ha! ha!. Ok, at last, you can see your dev dependencies in pubspec.yaml file like this.

dev_dependencies:flutter_test:
sdk: flutter
mockito: ^4.1.1

My main target for unit testing here to get check whether the get method or the post methods are working correctly. So I created a unit testing file like this.

Inside the main method, I need to test both get and post methods. So I created two groups for them. I could test two of them using two test cases but I didn’t because for future testing I should need to add more test cases under those two groups. Let’s discuss the first group that I created for the get method!

final Dio tdio = Dio();
DioAdapterMock dioAdapterMock;
APIHelper tapi;

First of all, we need to create a dio object to send and receive requests and responses. Then we need to create a mock Http client adapter for mock dio requests. Using that mock dio client we can get responses that we want. I created here ApiHelper instance including previous methods that we want to test.
When we need objects which are needed in many test cases we create those objects under setUp() method in the dart.

setUp(() {    
dioAdapterMock = DioAdapterMock();
tdio.httpClientAdapter = dioAdapterMock;
tapi = APIHelper.test(dio: tdio);
});

We need to create an API helper class object which has a mock dio object. Here I created the tapi object for that. My response body as follows.

final responsepayload = jsonEncode({"response_code": "1000"});

The HTTP response is my response to that get method here. The ResponseBody.fromString is a built-in dart class that I used to create the response here.

when(dioAdapterMock.fetch(any, any, any))
.thenAnswer((_) async => httpResponse);

Every time we call dioAdapterMock It will provide HTTP response as the Response.

final response = await tapi.get("/any url");      
final expected = {"response_code": "1000"};
expect(response, equals(expected));

When we are using mock dio, It will not use the true URL here in my test case. That’s why I mentioned here “any URL” inside the get method. If Our get method is correct It always gives the expected response as the response. Finally, we need to compare the expected response with the coming response.expect(response, equals(expected)) does that for me.

Now our test case is ready to run. Run and verify test case passing. If you don’t know how to run right click on the file name and select run test cases on the pop-up menu.

Now our get method is done. We need to build test cases for the post method in ApiHelper class. It’s test cases are the same as the get method above but when sending request It is included a body.

final response = await tapi.post("/any url", body: {"body": "body"});

This part is the only difference according to the previous get method test cases here. Now look my whole test class and understand It. I want you to know the main thing that how to mock dio requests. Ok, hope you got the idea about that!

Thanks for reading this article. Be sure to clap/recommend as much as you can and also share with your friends. It means a lot to me.

Also, Let’s become friends on LinkedIn and Github.

--

--