Let’s learn about mocking. In the previous episodes, you learned about unit testing. You wrote your first unit test. You also learned about the concept of mocking. In this episode, you will learn how to mock data. Mock, in general, means creating fake data or class.
Let us start but creating a Fake QuotesService class. in our quotes_change_notifier_test file. Let’s create a new class called MockQuotesService, which implements or extends the QuotesService class.
class MockQuotesService implements QuotesService {
}
When we extend or implement a class we need to implement all the methods of the class. In our case we need to implement the getQuotes method. You can do that by pressing cmd + . or Alt + Enter if on android studio on the class name and select Create Missing override(s).
@override
Future<void> getQuotes() async {
// Todo: adding a function which will return mock data
}
In this function, we will return the predictable data of the quotes we will create. Add the following mock data to the function.
return [
Quotes(
1,
'Test Quote 1',
'Test Author 1',
),
Quotes(
2,
'Test Quote 2',
'Test Author 2',
),
Quotes(
3,
'Test Quote 3',
'Test Author 3',
),
];
Here, we are returning a list of mock quotes data.
This is how you create a mock class. You can create a mock class for any class and use it to test. But as you guessed, there are better ways to create a mock class than this one. As the functionality increases, the mocks become more complex and difficult to maintain.
This is where third-party packages come in handy. Many packages can help you to create mock data. In our case, we will be using the mocktail package.
This mocktail package will help us to create mock data easily.
Before we begin, we need to add the latest version of the mocktail package to our pubspec.yaml file. So head to the pubspec.yaml file and add the mocktail package to the dev_dependencies section.
dev_dependencies:
flutter_test:
sdk: flutter
mocktail: <latest_version>
I’ll comment out the mockdata that we created because we will be using the mocktail package to create mock data.
Add the following code to the top of the test file to create a mock class file with the help of the mocktail package.
class MockQuotesService extends Mock implements QuotesService {}
And boom, you have a mock class. This is better than the previous method because you don’t have to implement all the methods of the class. You can create a mock class with the help of the mocktail package.
We now have a MockQuotesService class that we can pass into our QuotesNotifier variable.
Lets start by creating a variable of MockQuotesService class below the QuotesNotifier variable.
late MockQuotesService mockQuotesService;
We are not using sut variable because we are not creating a system under test. We are just creating a mock class.