Testing in Flutter

Sep 19 2023 · Dart 2.19.3, Flutter 3.7.6, Android Studio 2021.3.1, Visual Studio Code 1.7.4

Part 2: Write Unit Tests

08. Mock API Requests

Episode complete

Play next episode

Next
About this episode
Leave a rating/review
See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 07. Test Quotes Notifier Next episode: 09. Write Login Widget Test

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Previously you have written tests to test the Change Notifier. In this episode, you will write tests to test the API requests. API requests are an integral part of any app. And we may have some bugs in the HTTPS function. Testing API requests is essential.

test('Quotes Service MOCK API Test', () async{

});
final apiService = QuotesService();
import 'package:http/http.dart';
import 'package:http/testing.dart';

final client = MockClient();
Future<Response> _mockHTTP(Request request) async {
  // Todo write mock http function.
}
final client = (MockClient(_mockHttp));
final apiService = QuotesService(client);
final quotes = await apiService.getQuotes();
if (request.url.toString().startsWith('https://dummyjson.com/quotes')) {
        return Response(mockQuotes, 200,
            headers: {HttpHeaders.contentTypeHeader: 'application/json'});
      }

return throw Exception('failed');
final mockQuotes = jsonEncode(data);

final data = {
  "quotes": [
    {"id": 1, "quote": "I am best", "author": "Shree"}
  ],
};
expect(quotes.first.id, 1);
expect(quotes.first.author, 'Shree');
expect(quotes.first.quote, 'I am best');
test('Quotes Service MOCK API Test', () async {
      

  Future<Response> _mockHttp(Request request) async {
    if (request.url.toString().startsWith('https://dummyjson.com/quotes')) {
      return Response(mockQuotes, 200,
          headers: {HttpHeaders.contentTypeHeader: 'application/json'});
    }

    return throw Exception('failed');
  }
  final client = (MockClient(_mockHttp));
  final apiService = QuotesService(client);

  final quotes = await apiService.getQuotes();

  expect(quotes.first.id, 1);
  expect(quotes.first.author, 'Shree');
  expect(quotes.first.quote, 'I am best');
});