0Pricing
Flutter Mobile Development · Lekcja

Testy jednostkowe i mockowanie

Pisz szybkie, izolowane testy jednostkowe logiki biznesowej Fluttera i używaj mocków do testowania kodu zależnego od usług i API.

Testy jednostkowe i mockowanie to bezpłatna lekcja Flutter Mobile Development na CoddyKit. To lekcja 4 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej Flutter Mobile Development, a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs Flutter Mobile Development zawiera 4 lekcji w sumie.

Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.

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 / isNull
  • throwsException
  • contains(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 build

Stubbing 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.

Często zadawane pytania

Czy lekcja „Testy jednostkowe i mockowanie” jest bezpłatna?

Tak — pełny tekst „Testy jednostkowe i mockowanie” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu Flutter Mobile Development, przejdź na CoddyKit PRO. Kurs Flutter Mobile Development zawiera 4 lekcji w sumie.

Co nauczysz się w „Testy jednostkowe i mockowanie”?

Pisz szybkie, izolowane testy jednostkowe logiki biznesowej Fluttera i używaj mocków do testowania kodu zależnego od usług i API. Ćwiczysz Flutter Mobile Development z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.

Czy potrzebuję doświadczenia, aby zacząć Flutter Mobile Development?

Nie wymagamy żadnego doświadczenia. Flutter Mobile Development w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 4 z 4.

Ile czasu zajmuje lekcja „Testy jednostkowe i mockowanie”?

Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.

Czy mogę pisać i uruchamiać kod w tej lekcji Flutter Mobile Development?

Tak. Każda lekcja Flutter Mobile Development zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.

Wszystkie lekcje w tym kursie

  1. Zasady testowania widgetów
  2. Testy integracyjne
  3. Narzędzia i techniki debugowania
  4. Testy jednostkowe i mockowanie
← Powrót do Flutter Mobile Development