Test unitari e mocking
Scriva test unitari rapidi e isolati per la logica di business Flutter e usi i mock per testare il codice che dipende da servizi e API.
Test unitari e mocking è una lezione Flutter Mobile Development gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Flutter Mobile Development, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Flutter Mobile Development include 4 lezioni in totale.
Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.
The Testing Pyramid
You have seen widget and integration tests. At the base sits the fastest layer: unit tests that verify a single function or class in isolation.
- Many unit tests (fast)
- Fewer widget tests
- Even fewer integration tests (slow)
Anatomy of a Unit Test
A unit test uses test() and expect() from the test package.
import 'package:test/test.dart';
void main() {
test('adds two numbers', () {
expect(2 + 3, equals(5));
});
}Testing a Class
Instantiate the class under test and assert on its behaviour.
test('counter increments', () {
final counter = Counter();
counter.increment();
expect(counter.value, 1);
});Matchers
Matchers express expectations clearly.
equals(x)isTrue/isNullthrowsExceptioncontains(x)
expect(list, contains('apple'));
expect(() => parse('bad'), throwsFormatException);Grouping Tests
Use group() to organize related tests and share setup.
group('Cart', () {
test('starts empty', () { ... });
test('adds items', () { ... });
});setUp & tearDown
setUp runs before each test; tearDown runs after — perfect for fresh fixtures.
late Cart cart;
setUp(() => cart = Cart());
tearDown(() => cart.clear());The Problem of Dependencies
What if your class calls a real API or database? Tests would be slow and flaky. The solution is mocking — replacing dependencies with fakes you control.
Mockito Setup
Add mockito and build_runner, then annotate to generate mocks.
@GenerateMocks([ApiService])
void main() {}
// flutter pub run build_runner buildStubbing Methods
Use when(...).thenReturn(...) to define what a mock returns.
final mockApi = MockApiService();
when(mockApi.fetchUser()).thenAnswer((_) async => User('Ada'));Verifying Interactions
verify confirms a method was called the expected number of times.
await repository.loadUser();
verify(mockApi.fetchUser()).called(1);Testing Async Code
Mark the test body async and await futures, or use the completes matcher.
test('loads data', () async {
final result = await repo.load();
expect(result, isNotEmpty);
});Quick Check
Why would you use a mock in a unit test?
Recap
You learned unit testing and mocking:
- test/expect/matchers and group/setUp
- Mockito to generate mocks
- when().thenReturn and verify().called
- Testing async code
Unit tests give you fast confidence in your business logic.
Domande Frequenti
La lezione «Test unitari e mocking» è gratuita?
Sì — il testo completo di «Test unitari e mocking» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Flutter Mobile Development, passa a CoddyKit PRO. Il corso Flutter Mobile Development include 4 lezioni in totale.
Cosa imparerò in «Test unitari e mocking»?
Scriva test unitari rapidi e isolati per la logica di business Flutter e usi i mock per testare il codice che dipende da servizi e API. Eserciti Flutter Mobile Development con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.
Ho bisogno di esperienza per iniziare Flutter Mobile Development?
Non è richiesta alcuna esperienza precedente. Flutter Mobile Development su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.
Quanto tempo richiede la lezione «Test unitari e mocking»?
La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.
Posso scrivere ed eseguire codice in questa lezione Flutter Mobile Development?
Sì. Ogni lezione Flutter Mobile Development include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.
Tutte le lezioni di questo corso
- Principi del testing dei widget
- Test di integrazione
- Strumenti e tecniche di debugging
- Test unitari e mocking