Testing the Repository
The objective of a test suite is to completely test the functionality of the main code, including all code paths. Often, this gets measured in the form of “test coverage”, where we confirm:
- Whether all lines of code were executed
- Whether both the
true
andfalse
branches of anif
condition were taken - Whether a loop was executed 0, 1, and N times
- And so on
This project does not have 100% test coverage. Few projects presented in books have 100% test coverage.
This tutorial extends our test coverage a bit, by testing ToDoRepository
and our Room code. To do that, though, we will switch to writing instrumented tests. Room is designed to use Android’s SQLite by default, and so it is much easier to test this stuff when we run our tests on Android, rather than on our development machine.
Testing in instrumented tests is a lot like unit testing:
- We write JUnit tests with
@Test
functions and so on - We use assertions to determine whether our tests succeed or fail
- We can run the tests from Android Studio to see whether they work
On the other hand, there are substantial differences as well:
- The tests will run in an Android environment, on our chosen device or emulator
- The tests will be subject to some Android limitations, just as the regular Kotlin code that we might use on a server will not necessarily work in Android
This is a continuation of the work we did in the previous tutorial. The book’s GitLab repository contains the results of the previous tutorial as well as the results of completing the work in this tutorial.
Step #1: Renaming Our Instrumented Test
The existing instrumented test class, inside the androidTest
source set, is ExampleInstrumentedTest
. This is not a very useful name. Since we will be testing some of the functionality from ToDoRepository
, we should rename it to ToDoRepositoryTest
. And, since ToDoRepository
is in the repo
sub-package, we should have the test class mimic that.
In the androidTest
source set, right click over the com.commonsware.todo.repo
package and choose “New” > “Package” from the context menu. Fill in com.commonsware.todo.repo
for the name, then click “OK” to make this sub-package.
Then, drag-and-drop the ExampleInstrumentedTest
into this new repo
sub-package. The default values in the “Move” dialog should be fine, so just click “Refactor” to make the move.
Finally, right-click over the ExampleInstrumentedTest
class and choose “Refactor” > “Rename” from the context menu. Fill in ToDoRepositoryTest
as the replacement name, and click “Refactor” to make the change.
Prev Table of Contents Next
This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.