We are going to test the Change Notifier, which is part of the Riverpod package. We are using the Riverpod package to manage the state of the app. Having knowledge of Riverpod will be helpful for you to understand the code. If you are unfamiliar with Riverpod, I suggest you read this article on Rivepod.
As you know, we are using the Change Notifier class to notify the listeners when there is a change in the state. Let us write a test to check if the Change Notifier class is working fine.
Head to the test folder and create a new file called quotes_change_notifier_test. In this file, you will write your tests to test the Quotes Change Notifier class.
Like always, you will be writing your test inside the main function. So let us write the main function.
void main() {
}
Let’s create a late variable of type QuotesNotifier inside the main function.
late QuotesNotifier sut_quotesNotifier;
The sut stands for System Under Test. This is a common practice in testing. You will be writing your test for the QuotesNotifier class. So the QuotesNotifier class is the system under test.
Now let us write the setup function. The setup function is called before each test. So you can write the common code inside the setup function and initialize the variables you will use in the test.
We will initialize the QuotesNotifier class inside the setup function.
setUp(() {
sut_quotesNotifier = QuotesNotifier();
});
But the QuotesNotifier requires a QuotesService to be passed as an argument. And Passing the actual QuotesService won’t be a good option as it will slow the test. The data is from an external API and can change. Also, there can be many unexpected issues, like the API is down or the internet is not working. This can result in the test failing and resulting in a flakey test.
How to tackle it? By using a Mock. A mock is a fake implementation of a class or data. You can use a mock to test the class without actually using the class.
The following diagram will explain the concept of Mocking.
In real life, we get the data from an external source. In our case, we are getting the data from an API. But in testing, we break the connection with the external source and pass fake data, which can be controlled. We can test the class without actually using an external source. This is called mocking.
So let us learn how to create a mock in the Next Episode.