CodeBlanks Logo Icon CodeBlanks

Advanced mocking

Learn advanced mock and stub.

Advanced mocking

Advanced mocking mimics a dependency's behavior. when(mock.fetch()).thenReturn(5) sets a fixed return value; verify(mock.fetch()) checks call expectations.

Stub: returns a canned value when called. Spy: both returns and records calls. Mock: verifies call expectations.

These tools let you test domain logic without a real database or API. Tests are fast, repeatable and isolated.

Stub vs spy

A stub only returns a fixed value; it does not record calls. It is fast; used for simple return values.

A spy both returns and records calls. spy.callCount reads how many times it was called. A spy is used when behavior verification is needed.

A mock adds call expectation checks on top of a spy: verify(mock.fetch()).called(2). So mock = stub + spy + expectation checks.

Practice Define a MockUserService

Define a User class with final String name; User(this.name);. Define a class MockUserService with a User _stubbed; field, void stubFetch(User u) { _stubbed = u; } and User fetchUser() => _stubbed; methods. In main create final mock = MockUserService();; call mock.stubFetch(User('Ayşe'));; add print(mock.fetchUser().name);.

Starter code

main.dart
void main() {
  // define a User class (name field)
  // define a MockUserService class (stubFetch, fetchUser methods)
  // create a mock; stub a value; print via fetchUser
}

Sample solution

main.dart
class User {
  final String name;
  User(this.name);
}

class MockUserService {
  User _stubbed;
  void stubFetch(User u) {
    _stubbed = u;
  }
  User fetchUser() => _stubbed;
}

void main() {
  final mock = MockUserService();
  mock.stubFetch(User('Ayşe'));
  print(mock.fetchUser().name);
}

Expected output

Ayşe

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the mock parts

Term Meaning
Mock Fake class
when Stub start
thenReturn Return value
verify Call verification

2 What does when(mock.fetch()).thenReturn(5) do?

  • Runs fetch for real
  • Slows fetch down
  • Deletes fetch
  • Returns 5 when fetch is called Correct answer

Explanation: thenReturn returns a fixed value when called.

3 The thenReturn call

Question
when(mock.fetch()).____(5);
Answer
when(mock.fetch()).thenReturn(5);

Explanation: thenReturn sets a fixed return value.

All lessons in Expert