text
stringlengths
1
372
.thenanswer((_) async =>
http.Response('{"userId": 1, "id": 2, "title": "mock"}', 200));
expect(await fetchAlbum(client), isA<Album>());
});
test('throws an exception if the http call completes with an error', () {
final client = MockClient();
// use mockito to return an unsuccessful response when it calls the
// provided http.Client.
when(client
.get(uri.parse('https://jsonplaceholder.typicode.com/albums/1')))
.thenanswer((_) async => http.Response('Not found', 404));
expect(fetchAlbum(client), throwsException);
});
});
}
<code_end>
<topic_end>
<topic_start>
5. run the tests
now that you have a fetchAlbum() function with tests in place,
run the tests.
you can also run tests inside your favorite editor by following the
instructions in the introduction to unit testing recipe.
<topic_end>
<topic_start>
complete example
<topic_end>
<topic_start>
lib/main.dart
<code_start>
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
Future<Album> fetchAlbum(http.Client client) async {
final response = await client
.get(uri.parse('https://jsonplaceholder.typicode.com/albums/1'));
if (response.statuscode == 200) {
// if the server did return a 200 OK response,
// then parse the JSON.
return Album.fromJson(jsonDecode(response.body) as Map<String, dynamic>);
} else {
// if the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load album');
}
}
class album {
final int userId;
final int id;
final string title;
const album({required this.userId, required this.id, required this.title});
factory Album.fromJson(Map<String, dynamic> json) {
return album(
userId: json['userId'] as int,
id: json['id'] as int,
title: json['title'] as string,
);
}
}
void main() => runApp(const MyApp());
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
late final Future<Album> futureAlbum;
@override
void initState() {
super.initState();
futureAlbum = fetchAlbum(http.Client());
}
@override
widget build(BuildContext context) {
return MaterialApp(
title: 'fetch data example',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
),
home: scaffold(
appBar: AppBar(
title: const Text('Fetch data example'),
),
body: center(
child: FutureBuilder<Album>(
future: futureAlbum,
builder: (context, snapshot) {
if (snapshot.hasdata) {
return text(snapshot.data!.title);
} else if (snapshot.haserror) {
return text('${snapshot.error}');
}
// by default, show a loading spinner.
return const CircularProgressIndicator();
},
),
),
),
);