Mock
- Dart course
- Intermediate
- Lesson 86/116
- 5 min
Learn mocking with mockito.
Fakes with mocks
A mock is a fake version of a real dependency. It keeps external services (HTTP, databases) out of tests. The mockito package is common in Dart.
A mock class is written as class MockHttp extends Mock implements HttpClient {}. Then you set behavior with when(mock.get()).thenReturn('data').
So the test gets predictable results without a real network call. It is fast and stable.
when and verify
In mockito when(mock.fetch()).thenReturn('data') sets a method's return value. During the test calling mock.fetch() returns 'data'; no real call is made.
verify(mock.fetch()) checks whether the method was called. This is useful to probe interactions and to verify the expected flow.
In simple cases a hand-written fake class is enough; mockito is not always required.
Practice A fake WeatherService
Define an abstract class WeatherService with a String temperature() method. Write a FakeWeatherService implements WeatherService class whose temperature() returns '22C'. In main create a FakeWeatherService and print the result of temperature() with print.
Starter code
// Define the WeatherService abstract class
// Define the FakeWeatherService fake class
void main() {
// print the temperature result of the fake service
}Sample solution
abstract class WeatherService {
String temperature();
}
class FakeWeatherService implements WeatherService {
@override
String temperature() => '22C';
}
void main() {
var s = FakeWeatherService();
print(s.temperature());
}Expected output
22C
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does a mock do?
- Provides a fake dependency Correct answer
- Makes a real network call
- Sets up a loop
- Deletes a file
Explanation: a mock provides a fake dependency.
2 Importing mockito
import 'package:mockito/____.dart';
import 'package:mockito/mockito.dart';
Explanation: the mockito package is imported this way.
3 Mock parts
| Term | Meaning |
|---|---|
class FakeWeatherService |
Fake class |
when(...).thenReturn |
Behavior stubbing |
verify(...) |
Call verification |
Mock |
mockito base class |