Portrait

I2H3

Notes from work as an app developer for iPhones, iPads and Macs.

RSS Icon GitHub Mastodon

Result Builders To Mock File System

I need to maintain a virtual file system in a CoreData database. Setting up test scenarios is tiresome, so I made use of result builders and its nice.

There are a lot of tests to implement for a metadata database which I have to maintain for a file provider. At some point I really became tired of the verbose and cumbersome set up of test scenarios.

Usually it could look like this. And this even is a simplified and beautified example which leaves out a lot of properties. Also, it only includes one directory and one file from the root, not the more complex structures I have to work with.

let rootDirectory = try await database.fetchDirectory(byPath: .root)
let directory = try await database.createDirectory("Documents", in: rootDirectory)
let file = try await database.createFile(name: "Test.md", in: directory)

There are some great articles about result builders out there. I wrote a simple implementation and suddenly I can define my test scenarios very elegantly:

try database.mock {
    Directory("Documents") {
        File("Test.md")
    }
}
a memoji

At first, I was unsure whether I should just dump too many lines of code snippets here or set up an example project on GitHub which would cause a lot more work than a quick blog post again. I tried to scrape it together but just dumping it here is too much. On the other hand, I would be inclined to set up an example project on GitHub, if there is an interest for it.