Last Updated: 2018-06-11

Generating dynamic test cases with XCTest

While working on the article about resizable fonts it became clear that getting a preview of every font size without needing to use the accessibility inspector was going to be a pain.

Instead, it would be great to use UI tests and dynamically re-launch the app with a different size for each variation and save a screenshot in the build results. You can see the full example in the sample app for font size testing or check out the simpler example below.

Originally, I referenced this great article by Brian Coyner from 2015, but it seemed to be out of date a bit, and I was hopeful that with some of the recent work done on XCTest it would be possible to update things just a bit.

Here's a quick example:

fileprivate let _widgetSizes: [CGFloat] = [
    0.0, 1.0, 2.0, 4.0, 8.0,
]

struct WidgetExpander {
    var widgetSize: CGFloat

    var isValid: Bool {
        return true // ;) 
    }
}

class WidgetExpanderTest: XCTestCase {

    var widgetSize: CGFloat!

    override class var defaultTestSuite: XCTestSuite {
        let suite = XCTestSuite(forTestCaseClass: WidgetExpanderTest.self)

        _widgetSizes.forEach { size in
            // Generate a test for our specific selector
            let test = WidgetExpanderTest(selector: #selector(verifyWidget))

            // Each test will take the size argument and use the instance variable in the test
            test.widgetSize = size

            // Add it to the suite, and the defaults handle the rest
            suite.addTest(test)
        }
        return suite
    }

    // NOTE: Don't name this method with "test" or it'll 
    // still get picked up by the automatic test case generation.
    @objc func verifyWidget() {
        XCTAssertTrue(WidgetExpander(size: widgetSize).isValid)
    }
}

There's more to read!

Did this help solve your problem? If so, consider letting us know on Twitter. You should follow us for all the latest articles and updates:


Have you seen our latest project on Github?.

Sign up for our newsletter

Get an email when new content comes out! Emails are not sold and are used only for announcing updates to the site. Expect ~1-2 emails per month. Unsubscribe any time.