Database is a crucial part of any softwares nowadays, especially mobile applications. We use database to store various things, such as:

• app settings: to make it consistent between app launches.
• app context: to perserve the last screen user visited. (in case the app was killed, either intentionally by the user or automatically by the system to reclaim memory)
• data from a network reponse: to better support offline mode.
• anything you want to save for later submission when network is available.
• etc and etc…

Those are the things that make an app fast and responsive and eventually useful.

Therefore, we wanna make sure that our database works correctly. No mistakes or errors is tolerant here.

But how do we achieve that?

Well, you know, we write unit tests for it.

The database techonology I’m gonna use today is Realm. Although there are many other good alternatives out there that can do the job well, they’re just not as great as Realm. Here’s a couple of reasons why Realm is my database of choice:

• It’s fast, like… extremely fast. Look at this chart: (Source: qiita)

• It’s easy to use. The interface is very simple and swift-friendly. You can do all kinds of database operations with minimal efforts.
• It’s open source, mostly.
• If you encounter a bug, you can hop in and take a look at the underlying implementation. That would help you get an understanding of how things work and hopefully fix your bug.
• If you find something that can be improved, you can work on it and open a Pull-Request to contribute back to Realm. That’s powerful.

Realm is late to the game but proves to be one of the best mobile databases in the market, if not the best, apparently.

However, we’re not gonna learn how to use Realm today. Instead, we will try to write unit tests for it.

We’re gonna write a lot and cover most of Realm features. It may take time so make sure you’re passionate about it.

Alright, if that gets you excited, let’s jump in.

# Prerequisites:

Before we start, make sure you know:

# Setup Realm for testing:

When we’re testing, we may create/update or delete some records from the Realm database. We don’t want those changes to affect the production database. If we let that happens, it would become a disaster.

What we’re gonna do is we direct all Realm operations into a test database instead of the real one. Realm provides a very convenient way to do exactly just that.

This will point Realm to an in-memory database (namely “database A”) where we can freely experiment and do whatever we want. Since it’s in memory, it won’t affect the production database at all.

Now we need to call this Realm configuration line before any tests get executed. The ideal place is in the beforeSuite method:

Note: you can set the inMemoryIdentifier to anything as long as it’s not nil. In this case, I’m setting it to the Spec’s name so every Spec will use different in-memory database.

Additionally, we wanna clear out all records so that each test would start with a fresh empty database. Override the beforeEach and put in the code to delete everything within Realm:

We now have a clean and isolated testing environment. Let’s move on and write some real tests.

# 1. Testing models:

## 1.1. Test custom initializer:

Let’s say we have a Person model with 2 properties: name and age.

We also have a custom initializer to quickly set those properites:

Now how do we test this intializer method?

Well, we do it in 2 steps:

Let’s go ahead and add the test to your Spec file: (PersonSpec.swift in this case)

Fill in the test body with 2 steps we mentioned above:

Run the test (Cmd + U) and make sure that it passes.

## 1.2. Test relationships:

### To-One Relationships:

What we have:

Steps to test:

Create the test:

Fill in the test body:

Note that personName, personAge and dogName are just some constants defined elsewhere to make the code less duplicated.

### To-Many Relationships:

What we have:

Steps to test:

Create the test:

Fill in the test body:

### Inverse Relationships:

What we have:

Steps to test:

Create the test:

Fill in the test body:

## 1.3. Test ignored properties:

What we have:

Steps to test:

Create the test:

Fill in the test body:

Again, the personAddress and personHeight are just some constants defined elsewhere.

# 2. Testing CRUD operations:

## 2.1. Create:

What we have:

Steps to test:

Create the test:

Fill in the test body:

To read from database, we must have some data in it first. Let’s create a helper method to provide dummy data:

### Retrieving all objects:

What we have:

Steps to test:

Create the test:

Fill in the test body:

### Filtering:

What we have:

Steps to test:

Create the test:

Fill in the test body:

### Sorting:

What we have:

Steps to test:

Create the test:

Fill in the test body:

## 2.3. Update:

### Update properties:

What we have:

Steps to test:

Create the test:

Fill in the test body:

### Update with primary key:

What we have:

Steps to test:

Context 1: different primary key (id)

Context 2: same primary key (id)

Create the test:

Fill in the test body:

What we have:

Steps to test:

Create the test:

# Wrap up

These are just some simple use cases of Realm. They serve as the building blocks for writing more complex ones.

In a real-world scenario, it might require a combination of multiple Realm operations at a time. However, the testing approach is basically the same. You can extend it very easily.

Alright, that’s it for today. The sample project can be found at: https://github.com/hoang-tran/UnitTestRealm

I wish to hear more from you guys too. Please drop me a comment down below.

Have you ever used Realm? Do you write unit tests for it? Do you have any tips you wanna share with everyone?

## Subscribe to my blog

If you think this blog is useful, please subscribe to get notifications on my new posts.