Doing XCTests in a Playground

I can't believe no one has ever asked this (AFAIK).

I want to measure the time of my code. I have several alternate functions, so I want to separately measure each one and compare. How do I use the XCTest system with an Xcode Swift Playground. I guess I should import XCTest, but how do I define an appropriate testing class? And how do I run the test class without crashing? (My rough guess crapped out with a crash during the first function's measure call.)

1 Like

I recently did some Swift experiments in Playgrounds and was wondering the same thing. I followed a post by John Sundell . Here is a simplified snippet that runs from XCode (MacOS) Swift Playgrounds, using both XCTAsserts and measure blocks:

import Cocoa
import Foundation
import XCTest

class MyTestCase: XCTestCase {
    func testAssert() {
        XCTAssertTrue(false, "Unfortunate!")
    }
    
    func testMeasure() {
        let dateFormatter = DateFormatter()
        dateFormatter.dateStyle = .long
        dateFormatter.timeStyle = .short
        let date = Date()
        measure {
            let _ = dateFormatter.string(from: date)
        }
    }
}

MyTestCase.defaultTestSuite.run()

This produces the following output:

Test Suite 'MyTestCase' started at 2019-11-05 10:53:05.165
Test Case '-[__lldb_expr_10.MyTestCase testAssert]' started.
codable-experiment.playground:7: error: -[__lldb_expr_10.MyTestCase testAssert] : XCTAssertTrue failed - Unfortunate!
Test Case '-[__lldb_expr_10.MyTestCase testAssert]' failed (0.095 seconds).
Test Case '-[__lldb_expr_10.MyTestCase testMeasure]' started.
<unknown>:0: Test Case '-[__lldb_expr_10.MyTestCase testMeasure]' measured [Time, seconds] average: 0.000, relative standard deviation: 179.871%, values: [0.000165, 0.000016, 0.000011, 0.000010, 0.000010, 0.000009, 0.000009, 0.000009, 0.000009, 0.000009], performanceMetricID:com.apple.XCTPerformanceMetric_WallClockTime, baselineName: "", baselineAverage: , maxPercentRegression: 10.000%, maxPercentRelativeStandardDeviation: 10.000%, maxRegression: 0.100, maxStandardDeviation: 0.100
Test Case '-[__lldb_expr_10.MyTestCase testMeasure]' passed (0.794 seconds).
Test Suite 'MyTestCase' failed at 2019-11-05 10:53:06.055.
	 Executed 2 tests, with 1 failure (0 unexpected) in 0.889 (0.890) seconds
2 Likes