How to Run API Tests in Flutter
In Flutter, you can perform API testing to verify that your application correctly interacts with web services. This article will guide you through setting up and running API tests in Flutter.
Prerequisites
Before you begin, ensure you have the following:
- Flutter SDK: Make sure you have Flutter installed on your machine. You can check this by running
flutter --version
in your terminal. - Dart Packages: You’ll need the
http
package for making HTTP requests and thetest
package for writing and running tests.
1: Create a Flutter Project
If you haven’t already created a Flutter project, you can add the instructions from step 2. For the API there is not much require from the UI side of testing.
2: Add Dependencies
Open your pubspec.yaml
file and add the http
and test
dependencies:
dependencies:
flutter:
sdk: flutter
http: ^0.14.0
dev_dependencies:
test: ^1.16.0
Run flutter pub get
to install the new packages.
3: Create an API Service
Next, create a Dart file for your API service. This class will handle HTTP requests to your API. Create a file named api_service.dart
in the lib
folder:
import 'dart:convert';
import 'package:http/http.dart' as http;
class ApiService {
final String baseUrl;
ApiService(this.baseUrl);
Future<http.Response> get(String endpoint) {
return http.get(Uri.parse('$baseUrl$endpoint'));
}
Future<http.Response> post(String endpoint, Map<String, dynamic> data) {
return http.post(
Uri.parse('$baseUrl$endpoint'),
headers: {'Content-Type': 'application/json'},
body: json.encode(data),
);
}
Future<http.Response> patch(String endpoint, Map<String, dynamic> data) {
return http.patch(
Uri.parse('$baseUrl$endpoint'),
headers: {'Content-Type': 'application/json'},
body: json.encode(data),
);
}
Future<http.Response> delete(String endpoint) {
return http.delete(Uri.parse('$baseUrl$endpoint'));
}
}
4: Write API Tests
Now, create a test file for your API tests. Create a new folder named test
(if it doesn't already exist), and then create a file named api_service_test.dart
inside it:
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:test/test.dart';
import 'package:untitled1/api_service.dart';
void main() {
group('ApiService', () {
final apiService = ApiService('https://jsonplaceholder.typicode.com');
test('GET request returns a successful response', () async {
final response = await apiService.get('/posts/1');
print('GET response: ${response.body}'); // Print JSON response to console
expect(response.statusCode, 200);
expect(response.body, contains('userId'));
});
test('POST request creates a new post', () async {
final response = await apiService.post('/posts', {
'title': 'foo',
'body': 'bar',
'userId': 1,
});
print('POST response: ${response.body}'); // Print JSON response to console
expect(response.statusCode, 201);
final responseBody = jsonDecode(response.body);
expect(responseBody['title'], 'foo');
});
test('PATCH request updates an existing post', () async {
final response = await apiService.patch('/posts/1', {
'title': 'updated title',
});
print('PATCH response: ${response.body}'); // Print JSON response to console
expect(response.statusCode, 200);
final responseBody = jsonDecode(response.body);
expect(responseBody['title'], 'updated title');
});
test('DELETE request removes a post', () async {
final response = await apiService.delete('/posts/1');
print('DELETE response: ${response.body}'); // Print JSON response to console
expect(response.statusCode, 200);
expect(response.body, isEmpty);
});
});
}
Explanation of Tests
- GET Request: Verifies that the response status code is 200 and checks that the response body contains a specific key.
- POST Request: Tests creating a new resource and checks that the response status code is 201, confirming that the resource was created.
- PATCH Request: Tests updating an existing resource and checks that the response reflects the updated data.
- DELETE Request: Tests deleting a resource and verifies the empty response.
I have added logs to print the API response in the terminal. here is what the logs look like.
Step 5: Run the Tests
You can run your tests using the following command in the terminal.
flutter test test/api_service_test.dart
This command will execute all the tests in the specified test file. You will see the results in the console, along with any printed JSON responses.
Conclusion
API testing in Flutter is straightforward with the http
package and the test
framework. By following this guide, you can create and run tests for various HTTP methods, ensuring your application interacts correctly with web services. Incorporating API tests into your development process can greatly enhance the reliability of your applications.
Feel free to expand your tests based on the specific API endpoints you are working with and the data you expect to handle! If you have any questions or need further assistance, don’t hesitate to ask.
I have created a project on Github and added the code here.
Feel free to hit clap if you like the content. Happy Automation Testing :) Cheers. 👏