Open In App

How to Write TestCases For API Calls in Flutter?

Last Updated : 02 Aug, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Here we are going to build an app that calls an API and write test cases for it. But before we dive into it, let’s go through some basic concepts.

Software testing is a process in which we test code to ensure that it produces the expected results at any given instance.

Flutter tests consist of:

  1. Unit test - test for methods, functions, or classes
  2. Widget test - test for a single widget
  3. Integration test - test for the large part of or the entire application

As we are going to test a function that calls the API, we’ll be doing unit testing. Let’s create the app. You can create the app using the Flutter create command or use the IDE of your choice. In the app, we'll use the Numbers API, which will give random trivia about numbers, and then we will test the function that makes the API call. We are assuming you have some sort of experience with Flutter app development.

Step-by-step implementation

Step 1: Create a new Flutter Application

Create a new Flutter application using the command Prompt. To create a new app, write the following command and run it.

flutter create app_name

To know more about it refer this article: Creating a Simple Application in Flutter.

Step 2: Adding the Dependency

To add the dependency to the pubspec.yaml file, add http as a dependency in the dependencies part of the pubspec.yaml file, as shown below:

dependencies:
flutter:
sdk: flutter
http: ^1.4.0

Now, run the command below in the terminal.

flutter pub get

Or

Run the below command in the terminal.

flutter pub add http

Now let's create the app. You can remove all the contents of the main.dart file in the lib folder and remove the file in the test folder. Now we'll build the app in the main.dart file.

Dart
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

void main() {
  runApp(
    MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text(
            'GeeksForGeeks',
          ),
          backgroundColor: Colors.green,
        ),
        body: const MyApp(),
      ),
    ),
  );
}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
        future: getNumberTrivia(),
        builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const Center(
              child: CircularProgressIndicator(
                color: Colors.green,
              ),
            );
          } else if (snapshot.connectionState == ConnectionState.done) {
            return Padding(
              padding: const EdgeInsets.all(8.0),
              child: Center(
                child: Text(
                  snapshot.data.toString(),
                ),
              ),
            );
          } else {
            return const Center(
              child: Text(
                'Error Occurred',
              ),
            );
          }
        });
  }
}

Future<String> getNumberTrivia() async {
  Uri numberAPIURL = Uri.parse('http://numbersapi.com/random/trivia?json');
  final response = await http.get(numberAPIURL);
  if (response.statusCode == 200) {
    final Map triviaJSON = jsonDecode(response.body);
    return triviaJSON['text'];
  } else {
    return 'Failed to fetch number trivia';
  }
}

Run the app using the flutter run command or the run button in your IDE.

In order to write a test, we need to understand the method to be tested. Here we have a function named getNumberTrivia that calls an API that returns a JSON response of number trivia upon success, otherwise it returns an error message.

Now we can write two test cases first to test whether the successful API response returns a text containing the number trivia and second when the API call fails it returns an error message.

Before we start the test we need to understand that we should not make HTTP requests in the test. It's not recommended. Instead, we must use mocking or stubs. Luckily the HTTP package provides testing.dart file for us to use.

It is recommended that we create a folder called test at the root of the project and write our tests in that. It has already been present in our project since we created it. Make sure that you have flutter_test in your dev dependencies and http in the dependencies section of your pubspec.yaml file.

test_folder_structure

Before we test the function we should make the http dependency a parameter to the function which will help us in the mocking and stubs part of the test.

Dart
Future<String> getNumberTrivia(http.Client http) async {
  Uri numberAPIURL = Uri.parse('http://numbersapi.com/random/trivia?json');
  final response = await http.get(numberAPIURL);
  if (response.statusCode == 200) {
    final Map triviaJSON = jsonDecode(response.body);
    return triviaJSON['text'];
  } else {
    return 'Failed to fetch number trivia';
  }
}
Dart
class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
        future: getNumberTrivia(http.Client()),
        builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const Center(
              child: CircularProgressIndicator(
                color: Colors.green,
              ),
            );
          } else if (snapshot.connectionState == ConnectionState.done) {
            return Padding(
              padding: const EdgeInsets.all(8.0),
              child: Center(
                child: Text(
                  snapshot.data.toString(),
                ),
              ),
            );
          } else {
            return const Center(
              child: Text(
                'Error Occurred',
              ),
            );
          }
        });
  }
}

Create a dart file you can name it as get_number_trivia_unit_test.dart. Make sure that you put _test at the end of the file name. This helps Flutter understand the files for the test while using the flutter test command.

Some of the functions to know for the Flutter test. These functions come from the flutter_test package.

  • group(description, body): You can group test cases related to a particular function using the group function. You can write the description of the test in the description parameter and the body contains all the test cases.
  • test(description, describebody): You can write a test case using the test function to which you can provide the description in the parameter and the body will contain the test case itself.
  • expect(actual, matcher): You can test the output by using the expect method by providing it the output of the function as an actual parameter and expected output as a matcher.

There are two matchers you can find in the official documentation.

Dart
import 'dart:convert';
import 'package:flutter_test/flutter_test.dart';

// file which has the getNumberTrivia function
import 'package:flutter_unit_test/main.dart';
import 'package:http/http.dart';
import 'package:http/testing.dart';

void main() {
  group('getNumberTrivia', () {
    test('returns number trivia string when http response is successful',
        () async {
          
      // Mock the API call to return a json response with http status 200 Ok //
      final mockHTTPClient = MockClient((request) async {
        
        // Create sample response of the HTTP call //
        final response = {
          "text":
              "22834 is the feet above sea level of the highest mountain 
              in the Western Hemisphere, Mount Aconcagua in Argentina.",
          "number": 22834,
          "found": true,
          "type": "trivia"
        };
        return Response(jsonEncode(response), 200);
      });
      // Check whether getNumberTrivia function returns
      // number trivia which will be a String
      expect(await getNumberTrivia(mockHTTPClient), isA<String>());
    });

    test('return error message when http response is unsuccessful', () async {
      
      // Mock the API call to return an 
      // empty json response with http status 404
      final mockHTTPClient = MockClient((request) async {
        final response = {};
        return Response(jsonEncode(response), 404);
      });
      expect(await getNumberTrivia(mockHTTPClient),
          'Failed to fetch number trivia');
    });
  });
}

To run the test enter the following command in the terminal

flutter test 

Output:


Article Tags :

Similar Reads