Unit testing is an essential aspect of software development, ensuring that individual components of your application function as expected. In Flutter, unit testing is no different. Whether you are a beginner or looking to deepen your understanding, this guide will take you through writing unit test cases in Flutter, from the basics to more advanced techniques.
Before you can write unit tests, you need to set up your testing environment. This involves adding necessary dependencies and creating a test directory.
Open your pubspec.yaml file and add the test package under dev_dependencies. This package provides the core framework for writing and running tests.
dev_dependencies:
flutter_test:
sdk: flutter
test: ^1.16.0
In the root of your project, create a directory named test if it doesn’t already exist. This is where all your test files will reside.
Now that your environment is set up, write a basic unit test. Unit tests in Flutter are written using the test package.
1. Create a Dart file for Your Tests: Create a file named example_test.dart inside the test directory.
// test/example_test.dart
import 'package:test/test.dart';
void main() {
test('adds one to input values', () {
final calculator = Calculator();
expect(calculator.addOne(2), 3);
expect(calculator.addOne(-7), -6);
expect(calculator.addOne(0), 1);
});
}
class Calculator {
int addOne(int value) {
return value + 1;
}
}
This test checks if the addOne method of the Calculator class correctly adds one to various input values.
To run your test, use the terminal or your IDE’s test runner:
flutter test test/example_test.dart
You should see an output indicating whether your tests passed or failed.
As you become comfortable with basic tests, you can start writing more complex tests, including those that handle asynchronous code and mock dependencies.
Flutter’s test package supports asynchronous testing using the async and await keywords.
import 'package:test/test.dart';
Future<String> fetchUserOrder() =>
Future.delayed(Duration(seconds: 2), () => 'Large Latte');
void main() {
test('fetchUserOrder returns the correct order', () async {
var order = await fetchUserOrder();
expect(order, 'Large Latte');
});
}
In this example, fetchUserOrder is a function that simulates fetching an order from a remote server. The test ensures that the function returns the expected order after a delay.
To isolate the unit being tested, you may need to mock dependencies. The mockito package is commonly used for this purpose.
Add the mockito package to your pubspec.yaml:
dev_dependencies:
mockito: ^4.1.3
Example of mocking an HTTP client:
// test/user_test.dart
import 'package:test/test.dart';
import 'package:mockito/mockito.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
class MockClient extends Mock implements http.Client {}
void main() {
group('fetchUser', () {
test('returns a User if the http call completes successfully', () async {
final client = MockClient();
when(client.get(Uri.parse('https://jsonplaceholder.typicode.com/users/1')))
.thenAnswer((_) async => http.Response('{"id": 1, "name": "John Doe"}', 200));
expect(await fetchUser(client), isA<User>());
});
test('throws an exception if the http call completes with an error', () {
final client = MockClient();
when(client.get(Uri.parse('https://jsonplaceholder.typicode.com/users/1')))
.thenAnswer((_) async => http.Response('Not Found', 404));
expect(fetchUser(client), throwsException);
});
});
}
Future<User> fetchUser(http.Client client) async {
final response = await client.get(Uri.parse('https://jsonplaceholder.typicode.com/users/1'));
if (response.statusCode == 200) {
return User.fromJson(jsonDecode(response.body));
} else {
throw Exception('Failed to load user');
}
}
class User {
final int id;
final String name;
User({required this.id, required this.name});
factory User.fromJson(Map<String, dynamic> json) {
return User(
id: json['id'],
name: json['name'],
);
}
}
In this example, MockClient is used to simulate HTTP responses, allowing you to test the fetchUser function without making real network requests.
Testing widgets in Flutter ensures that your UI components render correctly and respond to user interactions as expected. The flutter_test package provides the tools needed for widget testing.
import 'package:flutter_test/flutter_test.dart';
import 'package:flutter/material.dart';
import 'package:my_app/my_widget.dart';
void main() {
testWidgets('MyWidget has a title and message', (WidgetTester tester) async {
await tester.pumpWidget(MyWidget(title: 'T', message: 'M'));
final titleFinder = find.text('T');
final messageFinder = find.text('M');
expect(titleFinder, findsOneWidget);
expect(messageFinder, findsOneWidget);
});
}
In this test, MyWidget is tested to ensure it correctly displays the provided title and message.
To keep your tests clean and DRY (Don’t Repeat Yourself), use setUp and tearDown for common setup and teardown code.
void main() {
setUp(() {
// Code to set up the test environment.
});
tearDown(() {
// Code to clean up after tests.
});
test('description', () {
// Test code.
});
}
The setUp function is called before each test, and the tearDown function is called after each test. This is useful for initializing and cleaning up resources.
void main() {
group('Calculator', () {
test('adds one to input values', () {
// Test code.
});
test('subtracts one from input values', () {
// Test code.
});
});
}
To tie everything together, here’s a complete example that includes various types of tests.
Calculator Class
// lib/calculator.dart
class Calculator {
int addOne(int value) => value + 1;
int subtractOne(int value) => value - 1;
Future<int> fetchRemoteValue() async {
await Future.delayed(Duration(seconds: 1));
return 42;
}
}
Calculator Tests
// test/calculator_test.dart
import 'package:flutter_test/flutter_test.dart';
import 'package:my_app/calculator.dart';
void main() {
group('Calculator', () {
final calculator = Calculator();
test('addOne adds one to input values', () {
expect(calculator.addOne(2), 3);
expect(calculator.addOne(-7), -6);
expect(calculator.addOne(0), 1);
});
test('subtractOne subtracts one from input values', () {
expect(calculator.subtractOne(2), 1);
expect(calculator.subtractOne(-7), -8);
expect(calculator.subtractOne(0), -1);
});
test('fetchRemoteValue returns 42 after a delay', () async {
expect(await calculator.fetchRemoteValue(), 42);
});
});
}
In this example, the Calculator class has methods for adding and subtracting one from a value, as well as a method for fetching a remote value. The tests verify that these methods work as expected.
Unit testing in Flutter plays a vital role in creating robust and error-free applications by verifying that each component functions as intended. This comprehensive guide has covered the essentials, from setting up the testing environment to advanced techniques like mocking dependencies and widget testing. By adhering to best practices and regularly running tests, developers can ensure higher code quality and reliability, leading to a smoother and more dependable user experience.
Nandkishor Shinde is a React Native Developer with 5+ years of experience. With a primary focus on emerging technologies like React Native and React.js. His expertise spans across the domains of Blockchain and e-commerce, where he has actively contributed and gained valuable insights. His passion for learning is evident as he always remains open to acquiring new knowledge and skills.
The team at Mindbowser was highly professional, patient, and collaborative throughout our engagement. They struck the right balance between offering guidance and taking direction, which made the development process smooth. Although our project wasn’t related to healthcare, we clearly benefited...
Founder, Texas Ranch Security
Mindbowser played a crucial role in helping us bring everything together into a unified, cohesive product. Their commitment to industry-standard coding practices made an enormous difference, allowing developers to seamlessly transition in and out of the project without any confusion....
CEO, MarketsAI
I'm thrilled to be partnering with Mindbowser on our journey with TravelRite. The collaboration has been exceptional, and I’m truly grateful for the dedication and expertise the team has brought to the development process. Their commitment to our mission is...
Founder & CEO, TravelRite
The Mindbowser team's professionalism consistently impressed me. Their commitment to quality shone through in every aspect of the project. They truly went the extra mile, ensuring they understood our needs perfectly and were always willing to invest the time to...
CTO, New Day Therapeutics
I collaborated with Mindbowser for several years on a complex SaaS platform project. They took over a partially completed project and successfully transformed it into a fully functional and robust platform. Throughout the entire process, the quality of their work...
President, E.B. Carlson
Mindbowser and team are professional, talented and very responsive. They got us through a challenging situation with our IOT product successfully. They will be our go to dev team going forward.
Founder, Cascada
Amazing team to work with. Very responsive and very skilled in both front and backend engineering. Looking forward to our next project together.
Co-Founder, Emerge
The team is great to work with. Very professional, on task, and efficient.
Founder, PeriopMD
I can not express enough how pleased we are with the whole team. From the first call and meeting, they took our vision and ran with it. Communication was easy and everyone was flexible to our schedule. I’m excited to...
Founder, Seeke
We had very close go live timeline and Mindbowser team got us live a month before.
CEO, BuyNow WorldWide
If you want a team of great developers, I recommend them for the next project.
Founder, Teach Reach
Mindbowser built both iOS and Android apps for Mindworks, that have stood the test of time. 5 years later they still function quite beautifully. Their team always met their objectives and I'm very happy with the end result. Thank you!
Founder, Mindworks
Mindbowser has delivered a much better quality product than our previous tech vendors. Our product is stable and passed Well Architected Framework Review from AWS.
CEO, PurpleAnt
I am happy to share that we got USD 10k in cloud credits courtesy of our friends at Mindbowser. Thank you Pravin and Ayush, this means a lot to us.
CTO, Shortlist
Mindbowser is one of the reasons that our app is successful. These guys have been a great team.
Founder & CEO, MangoMirror
Kudos for all your hard work and diligence on the Telehealth platform project. You made it possible.
CEO, ThriveHealth
Mindbowser helped us build an awesome iOS app to bring balance to people’s lives.
CEO, SMILINGMIND
They were a very responsive team! Extremely easy to communicate and work with!
Founder & CEO, TotTech
We’ve had very little-to-no hiccups at all—it’s been a really pleasurable experience.
Co-Founder, TEAM8s
Mindbowser was very helpful with explaining the development process and started quickly on the project.
Executive Director of Product Development, Innovation Lab
The greatest benefit we got from Mindbowser is the expertise. Their team has developed apps in all different industries with all types of social proofs.
Co-Founder, Vesica
Mindbowser is professional, efficient and thorough.
Consultant, XPRIZE
Very committed, they create beautiful apps and are very benevolent. They have brilliant Ideas.
Founder, S.T.A.R.S of Wellness
Mindbowser was great; they listened to us a lot and helped us hone in on the actual idea of the app. They had put together fantastic wireframes for us.
Co-Founder, Flat Earth
Ayush was responsive and paired me with the best team member possible, to complete my complex vision and project. Could not be happier.
Founder, Child Life On Call
The team from Mindbowser stayed on task, asked the right questions, and completed the required tasks in a timely fashion! Strong work team!
CEO, SDOH2Health LLC
Mindbowser was easy to work with and hit the ground running, immediately feeling like part of our team.
CEO, Stealth Startup
Mindbowser was an excellent partner in developing my fitness app. They were patient, attentive, & understood my business needs. The end product exceeded my expectations. Thrilled to share it globally.
Owner, Phalanx
Mindbowser's expertise in tech, process & mobile development made them our choice for our app. The team was dedicated to the process & delivered high-quality features on time. They also gave valuable industry advice. Highly recommend them for app development...
Co-Founder, Fox&Fork