title: Unit testing Room and LiveData
body: <p>I'm currently developing an app using the newly <a href="https://developer.android.com/topic/libraries/architecture/index.html" rel="noreferrer">Android Architecture Components</a>. Specifically, I'm implementing a Room Database that returns a <code>LiveData</code> object on one of its queries. Insertion and querying work as expected, however I have an issue testing the query method using a unit test.</p>
  <p>Here is the DAO I'm trying to test:</p>
  <p><strong>NotificationDao.kt</strong></p>
  <pre><code>@Dao
  interface NotificationDao {
  
      @Insert
      fun insertNotifications(vararg notifications: Notification): List&lt;Long&gt;
  
      @Query(&quot;SELECT * FROM notifications&quot;)
      fun getNotifications(): LiveData&lt;List&lt;Notification&gt;&gt;
  }
  </code></pre>
  <p>As you can tell, the query function returns a <code>LiveData</code> object, if I change this to be just a <code>List</code>, <code>Cursor</code>, or basically whatever then I get the expected result, which is the data inserted in the Database.</p>
  <p>The issue is that the following test will always fail because the <code>value</code> of the <code>LiveData</code> object is always <code>null</code>:</p>
  <p><strong>NotificationDaoTest.kt</strong></p>
  <pre><code>lateinit var db: SosafeDatabase
  lateinit var notificationDao: NotificationDao
  
  @Before
  fun setUp() {
      val context = InstrumentationRegistry.getTargetContext()
      db = Room.inMemoryDatabaseBuilder(context, SosafeDatabase::class.java).build()
      notificationDao = db.notificationDao()
  }
  
  @After
  @Throws(IOException::class)
  fun tearDown() {
      db.close()
  }
  
  @Test
  fun getNotifications_IfNotificationsInserted_ReturnsAListOfNotifications() {
      val NUMBER_OF_NOTIFICATIONS = 5
      val notifications = Array(NUMBER_OF_NOTIFICATIONS, { i -&gt; createTestNotification(i) })
      notificationDao.insertNotifications(*notifications)
  
      val liveData = notificationDao.getNotifications()
      val queriedNotifications = liveData.value
      if (queriedNotifications != null) {
          assertEquals(queriedNotifications.size, NUMBER_OF_NOTIFICATIONS)
      } else {
          fail()
      }
  }
  
  private fun createTestNotification(id: Int): Notification {
      //method omitted for brevity 
  }
  </code></pre>
  <p>So the question is: <em>Does anyone knows of a better way to perform unit tests that involve LiveData objects?</em></p>