<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Voloda on Medium]]></title>
        <description><![CDATA[Stories by Voloda on Medium]]></description>
        <link>https://medium.com/@voloda160?source=rss-17e7faee3cb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*hHaiWMkf3NatnvwS</url>
            <title>Stories by Voloda on Medium</title>
            <link>https://medium.com/@voloda160?source=rss-17e7faee3cb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 10:48:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@voloda160/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to Test Room DB Migrations Without an Emulator]]></title>
            <link>https://medium.com/@voloda160/how-to-test-room-db-migrations-without-an-emulator-2e3c54f60cd5?source=rss-17e7faee3cb------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e3c54f60cd5</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[database-testing]]></category>
            <category><![CDATA[ci]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[roomdb]]></category>
            <dc:creator><![CDATA[Voloda]]></dc:creator>
            <pubDate>Thu, 25 Jun 2026 17:45:23 GMT</pubDate>
            <atom:updated>2026-06-25T17:45:23.279Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*prPY5QuyIua7cTzC.png" /></figure><p>Testing Room Database migrations is a notorious pain point for Android developers. The traditional manual approach — installing an old version of the app, performing an upgrade, and praying it doesn’t crash — is incredibly time-consuming. It’s especially frustrating when it fails on the first attempt.</p><p>While Google recommends running instrumental tests on an emulator, this approach is resource-heavy, slow, and expensive to maintain in CI/CD pipelines. They didn’t mention that you can do it without an emulator.</p><p>Fortunately, there is a better way. You can run Room migration tests entirely within <strong>local unit tests using Robolectric</strong>. They run fast, require zero emulators, and can easily block broken pull requests before they reach your users. Here is how to set it up step-by-step.</p><h4><strong>Step 1: Export and Collect Your Schemas</strong></h4><p>The Room MigrationTestHelper relies on your exported schema JSON files to recreate older versions of your database. If you don&#39;t have schema exporting enabled, you will need to temporarily enable it, change your database version sequentially, and build the project to collect the history of your schemas (e.g., versions 1, 2, 3, 4, and 5).</p><p>Room only generates a schema JSON for the <em>current</em> version of your database compile. If you need historical schemas for versions already in production, use Git!</p><p>Check out the commit corresponding to your old version, enable schema export, and build the project to generate that version&#39;s JSON file. Copy it to a safe place, move to the next version, and repeat the process until you have collected all files from version 1 to your current version. Put them all into your app/schemas/ folder when you are done.</p><p>Check the documentation<br><a href="https://developer.android.com/training/data-storage/room/migrating-db-versions#kotlin_1">https://developer.android.com/training/data-storage/room/migrating-db-versions#kotlin_1</a></p><p>How to enable schema export:</p><pre>// top level gradle.kts<br>plugins {<br>    id(&quot;androidx.room&quot;) version &quot;$room_version&quot; apply false<br>}</pre><pre>//build.gradle.kts<br>//Gradle 9&gt;<br>plugins {<br>    id(&quot;androidx.room&quot;)<br>}<br><br>extensions.configure&lt;RoomExtension&gt; {<br>    schemaDirectory(&quot;$projectDir/schemas&quot;)<br>}<br><br><br>//build.gradle.kts<br>//Gradle 9&gt;<br>plugins {<br>  id(&quot;androidx.room&quot;)<br>}<br><br>room {<br>  schemaDirectory(&quot;$projectDir/schemas&quot;)<br>}</pre><pre>@Database(<br>    entities = [<br>        ChallengeEntity::class,<br>        CompletionDateEntity::class,<br>    ],<br>    version = DATABASE_VERSION,<br>    exportSchema = true,<br>)<br>abstract class AppDatabase</pre><pre>// Enable scheme export<br>@Database(<br>    entities = [<br>       ....<br>    ],<br>    version = DATABASE_VERSION,<br>    exportSchema = true, // enable<br>)<br>@TypeConverters(DateConverters::class, ListConverter::class)<br>abstract class AppDatabase</pre><p>Ensure exportSchema = true is set in your @Database annotation:</p><p>Sync the Gradle and just build the project. If everything is ok, you will find the JSON file with the schema. Please pay attention, the room will produce only the file for the current version of your database.<br>Save this file and do it again for each version where the schema is needed, including the latest.</p><p>So, I collected for 1, 2, 3, 4, 5. 5 is the latest.</p><h4><strong>Step 2: Configure Unit Test Dependencies</strong></h4><p>To make local unit tests read these schemas and simulate an Android environment, we need to link the schemas as test assets and pull in <strong>Robolectric</strong> and room-testing.</p><p>Depending on your Gradle version, configure your app/build.gradle.kts:</p><pre>// Gradle 8<br>android {<br>    ...<br>    sourceSets {<br>        // Adds exported schema location as test app assets.<br>        getByName(&quot;test&quot;).assets.srcDir(&quot;$projectDir/schemas&quot;)<br>    }<br>     KC// IMPORTANT!!!<br>     testOptions {<br>        unitTests {<br>            isIncludeAndroidResources = true<br>        }<br>    }<br>}<br><br>dependencies {<br>    // your other room dependencies, use latest version<br>    testImplementation(&quot;androidx.room:room-testing:2.8.4&quot;)<br>    testImplementation(&quot;junit:junit:4.13.2&quot;)<br>    testImplementation(&quot;org.robolectric:robolectric:4.16.1&quot;)<br>    testImplementation(&quot;androidx.test.ext:junit:1.3.0&quot;)<br>}<br><br>// Gradle 9<br>android {<br>   // Adds exported schema location as test app assets.<br>   sourceSets {<br>        getByName(&quot;test&quot;).assets.directories.add(&quot;$projectDir/schemas&quot;)<br>   }<br><br>   // IMPORTANT!!!<br>   testOptions {<br>        unitTests {<br>            isIncludeAndroidResources = true<br>        }<br>    }<br>}<br><br>dependencies {<br>    // your other room dependencies, use latest version<br>    testImplementation(&quot;androidx.room:room-testing:2.8.4&quot;)<br>    testImplementation(&quot;junit:junit:4.13.2&quot;)<br>    testImplementation(&quot;org.robolectric:robolectric:4.16.1&quot;)<br>    testImplementation(&quot;androidx.test.ext:junit:1.3.0&quot;)<br>}</pre><h4><strong>Step 3: Create the Migration Test</strong></h4><p>First, we will define a custom TestApplication class to give Robolectric a clean sandbox environment.</p><pre>import android.app.Application<br><br>class TestApplication : Application()</pre><p>Next, write the actual migration test. The MigrationTestHelper will read the schema JSONs from your asset folder, construct version 1 of your database, apply your migrations, and validate that the final schema perfectly matches version 5.</p><pre>import androidx.room.testing.MigrationTestHelper<br>import androidx.test.platform.app.InstrumentationRegistry<br>import com.my.always.crashed.app.data.database.AppDatabase<br>import org.junit.Rule<br>import org.junit.Test<br>import org.junit.runner.RunWith<br>import org.robolectric.RobolectricTestRunner<br>import org.robolectric.annotation.Config<br><br>@RunWith(RobolectricTestRunner::class)<br>@Config(sdk = [35], application = TestApplication::class)<br>class DatabaseMigrationTest {<br><br>    @get:Rule<br>    val helper: MigrationTestHelper = MigrationTestHelper(<br>        instrumentation = InstrumentationRegistry.getInstrumentation(),<br>        databaseClass = AppDatabase::class.java<br>    )<br><br>    @Test<br>    fun databaseMigrationSucceeds() {<br>        val dbPath = InstrumentationRegistry.getInstrumentation().targetContext.getDatabasePath(<br>            AppDatabase.DATABASE_NAME<br>        ).absolutePath<br><br>        helper.createDatabase(<br>            name = dbPath,<br>            version = 1<br>        ).apply {<br>            close()<br>        }<br><br>        helper.runMigrationsAndValidate(<br>            name = dbPath,<br>            version = AppDatabase.DATABASE_VERSION,<br>            validateDroppedTables = true,<br>            migrations = AppDatabase.migrations<br>        ).apply {<br>            close()<br>        }<br>    }<br>}</pre><p>Reference AppDatabase Structure</p><p>For context, your database companion object should expose your array of migrations like this:</p><pre>@Database(<br>    entities = [<br>    ],<br>    version = DATABASE_VERSION,<br>    exportSchema = true // should be enabled<br>)<br>abstract class AppDatabase : RoomDatabase() {<br><br>    companion object {<br><br>        const val DATABASE_NAME = &quot;mypath_database&quot;<br>        const val DATABASE_VERSION = 5 // latest version<br><br>        val migrations: Array&lt;Migration&gt;<br>            get() = arrayOf(<br>                MIGRATION_1_2,<br>                MIGRATION_2_3,<br>                MIGRATION_3_4,<br>                MIGRATION_4_5<br>            )<br><br>        fun getInstance(context: Context): AppDatabase {<br>            return Room.databaseBuilder(<br>                context.applicationContext, AppDatabase::class.java, DATABASE_NAME<br>            )<br>                .addMigrations(*migrations)<br>                .build()<br>        }<br>    }<br>}</pre><h4><strong>Step 4: Run, Verify, and Automate</strong></h4><ul><li>Run ./gradlew clean to ensure a fresh environment.</li><li>Run your local unit tests via Android Studio or through the terminal: ./gradlew testDebugUnitTest or by play button.</li></ul><h4><strong>Troubleshooting Schema Missing Errors</strong></h4><p>If Robolectric struggles to locate the schemas dynamically via the sourceSets configuration and project clean didn’t work, you can work around it manually:</p><ol><li>Create a directory named app/src/test/assets/.</li><li>Inside it, mimic your database’s package path (e.g., app/src/test/assets/com/yourpackage/app/data/database/AppDatabase/).</li><li>Copy your schema JSON files directly into that terminal folder, run your tests, and delete them afterwards once the build caching issue is resolved.</li></ol><h4>Step 3: Commit</h4><p>Once the tests pass, <strong>commit your schema files and the test code</strong> to your Git repository.</p><p>Once tests are successful, commit the test and schemas to your remote repository.</p><h4><strong>Step 5: Automate</strong></h4><p>If you have already run your unit test in CI/CD, no actions. Please consider running a unit test in the scope of your CI/CD. You will be able to catch crashes before making the pull request and be more confident in production.</p><h3>Benefits</h3><ul><li>Tests run in seconds directly from Android Studio, so you can actually verify migrations locally before pushing code.</li><li>You don’t need a heavy emulator instance in your pipeline. Any lightweight, standard CI runner can run these tests on every pull request.</li><li>It automatically catches mismatched schemas, typo-ridden SQL scripts, or missing columns before they hit production.</li><li>It takes less than an hour to set up, but it completely removes the guesswork from releasing database updates.</li></ul><h3><strong>Useful links</strong></h3><p><a href="https://developer.android.com/training/data-storage/room/testing-db">https://developer.android.com/training/data-storage/room/testing-db</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e3c54f60cd5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>