Testing Room Database in Android using JUnit
In this article, we are going to test the Room Database in android. Here we are using JUnit to test our code. JUnit is a “Unit Testing” framework for Java Applications which is already included by default in android studio. It is an automation framework for Unit as well as UI Testing. It contains annotations such as @Test, @Before, @After, etc. Here we will be using only @Test annotation to keep the article easy to understand. Note that we are going to implement this project using the Kotlin language.
Step by Step Implementation
Step 1: Create a new project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.
Step 2: Add Dependencies
Inside build.gradle (project) add the following code under dependencies. It contains dependencies of Room Db, Coroutiene, JUnit, Truth, and others.
Before Writing our test lets first create Room Database
Step 3: Create a new model class “Language.kt”
Create a new class “Language.kt” and annotate it with @Entity and pass the table name.
Step 4: Create dao interface
Create a new class “LanguageDao.kt” and annotate it with @Dao.Comments are added for a better understanding of the code.
Step 5: Create a Database class
Create a new abstract class “LanguageDatabase.kt” and annotate it with @Database. Below is the code of LanguageDatabase.kt class comments are added for better understanding.
Step 6: Create a Test class
In order to create a test class of LanguageDatabase.kt right-click on LanguageDatabase then click generate and then select the test. A dialog will open, from the dialog choose Testing library as JUnit4 and keep the class name as default that is LanguageDatabaseTest, and click ok. After that, another dialog will open to choose the destination directory, choose the one which has ..app\src\AndoidTest\. because our test class requires context from the application. Below is the screenshot to guide you create the test class.
Step 7: Working with LanguageDatabaseTest.kt class
Go to LanguageDatabaseTest.kt file and write the following code. Comments are added inside the code to understand the code in more detail.
Step 8: Run Tests
To run the test case click on the little run icon near the class name and then select Run LanguageDatabaseTest. If all the test cases pass you will get a green tick in the Run console. In our case, all tests have passed.
Github Repo here.