Step #5: Writing and Running More Tests

That test function tests our ability to save() an item to an empty repository. Now, let’s test some more scenarios.

Add these two test functions to ToDoRepositoryTest:

  @Test
  fun canModifyItems() = runBlockingTest {
    val underTest = ToDoRepository(db.todoStore(), this)
    val testModel = ToDoModel("test model")
    val replacement = testModel.copy(notes = "This is the replacement")
    val results = mutableListOf<List<ToDoModel>>()

    val itemsJob = launch {
      underTest.items().collect { results.add(it) }
    }

    assertThat(results[0], empty())

    underTest.save(testModel)

    assertThat(results[1], contains(testModel))

    underTest.save(replacement)

    assertThat(results[2], contains(replacement))

    itemsJob.cancel()
  }

  @Test
  fun canRemoveItems() = runBlockingTest {
    val underTest = ToDoRepository(db.todoStore(), this)
    val testModel = ToDoModel("test model")
    val results = mutableListOf<List<ToDoModel>>()

    val itemsJob = launch {
      underTest.items().collect { results.add(it) }
    }

    assertThat(results[0], empty())

    underTest.save(testModel)

    assertThat(results[1], contains(testModel))

    underTest.delete(testModel)

    assertThat(results[2], empty())

    itemsJob.cancel()
  }

These use all the same techniques that the first test function did. The can modify items() test function confirms that if we save() a modified version of our model, that the repository is updated with that modification. can remove items() confirms that if we delete() a model that was saved earlier, that the model is removed from the repository.

If you run all the test functions for ToDoRepositoryTest, they should all succeed.

There are lots of other tests that we could write:

However, for the purposes of showing how to test our repository, these three test functions will be enough.


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.