Copying fixture data to iOS app during test

599 views Asked by At

I have a set of fixture data for my app that I'd like to use for unit testing, but in order to do so, I have to copy it to the application's Documents/ directory, and I'm at a loss as to how to do that in a reproducible manner. So far all I've been able to do is print a log message that shows where the current Documents directory is (in the simulator) and then manually copy data into that directory. This is obviously less than ideal.

I could also copy my fixture data to a known directory (e.g., "/tmp/MyAppFixtures"), but then I'd have to be able to programmatically get the path to my fixture data (e.g., "~/Projects/MyApp/Fixtures"). I don't want to hard-code in paths that are lower than the root of my project, but I can't figure out how to get the project root into my unit tests.

If I were using Makefiles for this, I could simply call /bin/pwd or something similar to figure out the project root, and then I could use that in a -D to the compiler, but I can't see how to do this via Xcode's project files.

However the solution looks, what I want is to be able to be able to point my app at my fixture documents for testing purposes so that I can test loading, saving, versioning, and other such things directly.

1

There are 1 answers

0
Brian Cully On BEST ANSWER

After digging around for a while, I've found that, while in the test environment (i.e., when you execute the Product -> Test menu item), you can use +[NSBundle bundleForClass] on your unit test's class to find the DerivedData directory where your source files, including fixtures, are copied.

In Swift, this is done with:

class SomeTests: XCTestCase {
    var fixturesURL: NSURL {
        get {
            let testBundle = NSBundle(forClass: self.dynamicType)
            return testBundle.URLForResource("Fixtures", withExtension: nil)!
        }
    }
}

If you have a "Fixtures" subdirectory in the folder that belongs to your test target (iow, if you have a project named "Foo" and a "FooTests" target for your unit tests, then a directory named "Foo/FooTests/Fixtures") the code above will point to the data in your Fixtures folder.

It's worth noting that the URL will actually be something in DerivedData, but that data is copied from your project directory when Xcode builds your target, so you don't have to worry about that.