Building Android Local Unit Tests

On Android unit tests can either run on an Android device (or emulator), so called instrumented tests, or they can run on your local development machine. Running local unit tests is typically much faster.

To learn how local unit tests for Android work in general have a look at the Android developers documentation on Building Local Unit Tests. Read along to learn how to use ObjectBox in your local unit tests.

Set Up Your Testing Environment

In your app’s build.gradle file, you need to add the native ObjectBox library for your operating system to your existing test dependencies:

It is fine to add each native library if you want to run your tests on each of these operating systems.

Local unit tests are currently only supported on 64-bit operating systems.

Create a Local Unit Test Class

You create your local unit test class as usual under module-name/src/test/java/. To use ObjectBox in your test methods you need to build a BoxStore instance using the generated MyObjectBox class of your project. You can use the directory(File) method on the BoxStore builder to ensure the test database is stored in a specific folder on your machine. To start with a clean database for each test you can delete the existing database using BoxStore.deleteAllFiles(File).

The following example shows how you could implement a local unit test class that uses ObjectBox:

To help diagnose issues you can enable log output for ObjectBox actions, such as queries, by specifying one or more debug flags when building BoxStore.

Testing Entities with Relations

To test entities that have relations, like ToOne or ToMany properties, you must modify your entities first. These modifications are normally done by the ObjectBox plugin byte-code transformer. But the transformer does not run for local unit tests (it does for instrumented tests).

For each entity that has relations you need to initialize each ToOne and ToMany field. In addition you need to add a transient BoxStore field named __boxStore.

An example for a modified entity class might look like this:


Next steps

Get the Android Studio objectbox-example project with a full local unit test example.


Spread the love
Sign up for fresh ObjectBOX news here. No spam, just fresh developer news once in a while.