Sub topic 2
Testing asynchronous code
This chapter assumes you know Dart's async and await, can write a StatefulWidget, and can run flutter test. You will test asynchronous code, make dependencies replaceable, and then test a widget.
Testing asynchronous code
Make the test function async and await the result. Without await, the test can finish before the Future completes and report a false pass.
import 'package:flutter_test/flutter_test.dart';
Future<int> fetchScore() async => 42;
void main() {
test('fetchScore returns 42', () async {
expect(await fetchScore(), 42);
});
}Making code testable with dependency injection
Dependency injection means a class receives its collaborators through its constructor instead of creating them. A test can then pass in a replacement.
abstract class UserRepository {
Future<String> fetchName(int id);
}
class Greeter {
Greeter(this.repository);
final UserRepository repository;
Future<String> greet(int id) async {
final name = await repository.fetchName(id);
return 'Hello, $name!';
}
}Replacing dependencies with fakes and mocks
A fake is a hand-written class that implements the interface. A mock, from the mocktail package, records calls and lets you stub answers. The following test uses a mock, stubs fetchName, and verifies the call.
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
class MockUserRepository extends Mock implements UserRepository {}
void main() {
test('greets the user by name', () async {
final repository = MockUserRepository();
when(() => repository.fetchName(1)).thenAnswer((_) async => 'Ada');
final greeter = Greeter(repository);
expect(await greeter.greet(1), 'Hello, Ada!');
verify(() => repository.fetchName(1)).called(1);
});
}Widget tests: building a widget in a test
A widget test uses testWidgets, which passes a WidgetTester. Call pumpWidget to build the widget inside a MaterialApp.
Finding widgets and asserting on them
Finders locate widgets, such as find.text('0') or find.byIcon(Icons.add). Matchers such as findsOneWidget check the result. After a tap, call tester.pump() to rebuild the frame before you assert.
testWidgets('tapping the button increments the counter', (tester) async {
await tester.pumpWidget(const MaterialApp(home: CounterPage()));
expect(find.text('0'), findsOneWidget);
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
expect(find.text('1'), findsOneWidget);
});Exercise
In the Greeter test, what would break if you removed the await before greeter.greet(1)?
Show answer
The expect would compare a pending Future with the string, so the assertion fails or the test ends before the greeting is computed. Awaiting the Future fixes this.