Unit Testing With JUnit in Kotlin

I’m fairly new to using MongoDB, but I’m finding it quite difficult to find a way to test my Mongo code. Particularly static methods, like Credentials.emailPassword or Realm.init. For example, how would I test the following using JUnit in Kotlin?

override suspend fun login(email:String, password: String) {
    val completableDeferred = CompletableDeferred<App.Result<User>>()
    val credentials = Credentials.emailPassword(email, password)
    app.loginAsync(credentials) {
        completableDeferred.complete(it)
    }
    onResult(completableDeferred, LoginException())
}

private suspend fun onResult(completableDeferred: CompletableDeferred<App.Result<User>>, exception: MyException) {
    val result = completableDeferred.await()
    if (!result.isSuccess) {
        result.error.errorMessage?.let { exception.errorMessage = it }
        throw exception
    }
}

Thank you for any help.

Hi Joe!

Welcome to the forum.

I’m actually putting together a guide on this exact subject right now for the Android SDK, but in the meantime, I can point you toward the testing environment we use to test the code snippets that occur in the documentation: https://github.com/mongodb/docs-realm/tree/master/examples/android/sync

Basically, if you’re trying to test functionality that requires a connection to your backend Realm App, you have two options:

  1. Mock the backend completely, as we’ve demonstrated here.
  2. Hit your actual backend (or perhaps a qa or development version of your backend) in an integration test suite. That’s what we use for the documentation code snippet tests. The critical piece here is found in the RealmTest class, which sets up an ephemeral Realm App with a backend for each test case. Because Realm depends on a Looper thread for syncing data changes between Realm Database and your app, you’ll need to either use the UI thread (and, as a consequence, use Async functions for most tests) or set up your own background Looper thread with synchronous API calls. I would recommand sticking with whatever matches your app logic best.

Personally I like the idea of end-to-end testing since backend function logic often ends up intermingled with frontend client logic, but depending on your use case, mocking might be your best option.

I’ve spent a good amount of time over the past few months setting up tests for Realm apps, so happy to help with any other questions on the subject.

Hi Nathan, I would ideally want to mock the backend, so these examples are great, thank you. I’ll let you know if I have any questions.