Testing came up in many of the mobile adverts we read, including a junior role: unit tests, widget or UI tests, and sometimes test driven development. Teams want developers who can prove their code works and find bugs calmly. Flutter makes both easier than you might expect.
Three levels of tests
- Unit tests check a single function or class, with no screen. For example: does
cartTotaladd prices correctly, and does it return 0 for an empty cart? They run in seconds. - Widget tests build one widget or screen in a fake environment and check what appears. For example: when I tap "Add", does the count go from 0 to 1?
- Integration tests run the whole app on a real phone or emulator, tapping through a full journey. They are slower, so you write fewer of them.
Most of your tests should be unit and widget tests.
A unit test
Put tests in the test folder. Flutter projects include the flutter_test package for this:
import 'package:flutter_test/flutter_test.dart';
import 'package:shop/cart.dart';
void main() {
test('total adds item prices', () {
final cart = Cart()..add(15)..add(20);
expect(cart.total, 35);
});
test('empty cart total is zero', () {
expect(Cart().total, 0);
});
}