Unit-Testing Drift Database (DAOs)
The previous article went over the basics of testing Drift database, in this article, we will go over unit testing when there are DAOs involved. As you will see there’s not much difference with how the tests are structured. Let’s jump into it.
Create Todo’s DAO
This creates the basic class setup. I assume you are familiar with what is going on here. If not you can refer to this article from the official docs. Next, we will bring the methods we had in the AppDatabase
class into TodosDAO
such that it looks like this.
At this point, the test file will be complaining of missing methods. Opening the test file you will realize this is because on the tests we are referencing methods that should be under AppDatabase
class instance.
TodosDAO Tests
We can reuse the same tests on the app_database_test.dart
. In todos_dao_test.dart
we copy over the tests but we modify them to be referencing the TodosDao
.
Note that when testing through the DAO we are referencing the DAO class. If you have layered your app and you have the data source layer getting the data from the database then it becomes easy to create to test. You can choose to Mock the class or just use it as it is. I have found no issue with using the class directly without mocking it as the response is quite okay as the database under test is from memory which is fast enough.
As you can see testing the DAOs is not different from the previous example. Hope you learnt something new. Leave a clap on your way out. 😊
Until we meet it again let's keep up the technological revolution age alive.