Easy Step to Unit Test Appwrite SDK on Flutter with Mockito
A practical guide to writing unit tests for Appwrite SDK on Flutter with Mockito
Appwrite is an open-source (OSS) Backend as a Service that is aiming to abstract the complexity of common, complex, and repetitive tasks required for building a modern app. Appwrite can be used as an alternative to Firebase with a bunch of features like authentications, database, storage, functions, and real-time support. Also, it provides SDK for almost all platforms like web, Android, iOS, Flutter, etc.
Although we using SDK for developing an app. Unit testing is still important to do to test if our app is connected well or not to that SDK. So, in this article, I want to show you how to create a unit test on your Flutter project when using Appwrite as the SDK for your backend.
If you are new to term unit testing, you can read my previous article about Flutter testing here.
Step 1 — Get Mockito Plugin
Because in a unit test we don’t execute a real function. So, to be able to unit test a service like Appwrite is that we need to create a mock for that service. To do that we need a plugin called Mockito
Let’s add mockito
to our dev_dependencies
on pubspec.yaml
file.
...
dev_dependencies:
flutter_test:
sdk: flutter build_runner: ^2.1.7
mockito: ^5.1.0
...
Besides mockito
, we also need build_runner
it because mockito will generate the mock file.
Step 2 — Create Appwrite Mock
After getting the plugins we need, the next step is to generate a mock of our service. For example, I want to create a repository for authentication stuff. So, I will generate a mock for the Account
from Appwrite SDK.
To generate a new mock file, we use @GenerateMocks()
annotation on our test file. After that, we need to run build_runner
to start generating the mock file. This command will generate a new file like auth_repository_test.mocks.dart
flutter packages pub run build_runner build
Step 3 — Write Test
Now, we are ready to write our test. As an example, I will write a test for the login function. Here is what my test file for auth_repository_test.dart
looks like:
MockAccount
is taken from the mock file that we generated previously. On the AuthRepositoryImpl
, I pass the _mockAccount
as the dependency.
Step 4 — Write Actual Code
The last step is to write the actual repository code. Here is what my auth_repository.dart
file looks like:
By the way, Appwrite also provides AppwriteException
class. It’s helpful if you want to create more rich error handling for your app. For example, wrong password warning, email already in use warning, etc.
So, that's a step-by-step writing unit testing for your Flutter project when you use Appwrite as the SDK for making your life easier while creating an app solo. I use Test-Driven Development method when writing that unit test. If you are curious about TDD, you can read more here:
If you have any questions, feel free to start a discussion.
Thanks for reading.