How to check if data is inserted in Room Database

后端 未结 7 2663
执念已碎
执念已碎 2021-02-19 22:07

I am using Room Database from the new Architecture components in my project. I am adding some data through dao, but when trying to retrieve it I am not getting it. Can you pleas

7条回答
  •  旧巷少年郎
    2021-02-19 22:32

    There are multiple ways you can test that.

    1. As @Ege Kuzubasioglu mentioned you can use stetho to check manually (Need minor change to code).
    2. Pull database file from "data/data/yourpackage/databases/yourdatabase.db" to your local machine and use any applications to read the content inside the database. I personally use https://sqlitebrowser.org/. Pulling database file can be done either using the shell commands or use "Device File Explorer" from android studio.

    3. Write TestCase to see if it is working. Here is an example of test case from one of my projects.

      // Code from my DAO class

      @Insert(onConflict = OnConflictStrategy.REPLACE) public abstract Long[] insertPurchaseHistory(List MusicOrders);

    //My Test Case @Test public void insertPurchaseHistoryTest() {

        // Read test data from "api-responses/music-purchase-history-response.json"
        InputStream inputStream = getClass().getClassLoader()
                .getResourceAsStream("api-responses/music-purchase-history-response.json");
        // Write utility method to convert your stream to a string.
        String testData = FileManager.readFileFromStream(inputStream);
    
        // Convert test data to "musicOrdersResponse"
        MusicOrdersResponse musicOrdersResponse = new Gson().fromJson(testData,MusicOrdersResponse.class);
    
        // Insert inmateMusicOrders and get the list of
        Long[] rowsInserted = tracksDao.insertPurchaseHistory(musicOrdersResponse.getmusicOrders());
        assertThat(rowsInserted.length,Matchers.greaterThan(0));
    }
    

提交回复
热议问题