Published:

Tagged: Swift iOS TDD

TDD-ing your Realm objects in Xcode Playgrounds

In 2 previous posts, I’ve shown how to do Test-Driven Development (TDD) and how to use 3rd party frameworks in Xcode Playgrounds. This blog post ties them together so you’ll need to read those 2 posts first to make sense of this one.

If you’ve never used Realm Mobile Database before, head over to Realm Swift documentation pages. In short, it is a fast, open-source alternative to SQLite and CoreData — allows you to store your data fast in a cross-platform format. There is also a Realm Browser app that can be downloaded from the Mac App Store.

The Task object and TestCase

The Task object and TestCase

Let’s go through this one step at a time.

Import PlaygroundWrapper and RealmSwift

As mentioned in Using 3rd party frameworks in Xcode Playgrounds, this technique allows us to bring Realm support into the playgrounds.

Task realm object

I’ve created a simple Realm object with one property — Realm objects must have at least one property. In my case this an uuid that gets a randomly generated string when created.

class Task: Object {
    dynamic var uuid = UUID().uuidString
}

TaskTests

As described in TDD in Xcode Playgrounds, I’ve created a subclass of XCTestCase and run a test suite.

The class also contains 2 properties that will help with the testing.

class TaskTests: XCTestCase {
    var realm: Realm!
    var task: Task!
    
    ...
    
}

TaskTests.defaultTestSuite().run()

The setup

The “magic” here is the use of in memory Realm databases with a random identifier. This ensures that a new fresh realm is created before each test.

Setting the Realm.Configuration.defaultConfiguration allows us to not having to store the configuration for later use — we can simply address the realm as Realm().

override func setUp() {
    super.setUp()
    Realm.Configuration.defaultConfiguration = 
        Realm.Configuration(inMemoryIdentifier: UUID().uuidString)

    task = Task()
    realm = try! Realm()
    try! realm.write {
        realm.add([task])
    }
}

The test: testSetup()

Fairly straigtforward — we’re testing that we have one and only one realm objects of type Task.

func testSetup() {
    let tasks = try! Realm().objects(Task.self)
    XCTAssertEqual(tasks.count, 1)
}

From here onwards, the world is your oyster…

The project can be found on github: https://github.com/pardel/tdd-realm-playgrounds.

But is it fast?

Oh yes, it’s fast: https://realm.io/news/introducing-realm/#fast - Realm was designed and built for performance.

Last but not least, imagine TDD-ing with Core Data, Playgrounds or not. 🤓