Ric Pruss
Ric Pruss

Reputation: 446

How do you call XCTest in a Swift Playground?

I was looking at Bendyworks' article on Unit testing with Swift: http://bendyworks.com/unit-testing-in-swift/

and as you do with Swift I took the code and threw it in Playground to have poke at it.

import Cocoa

class Firewood {
    var charred: Bool
    init()  {
        println("initializing our firewood")
        charred = false
    }
    func burn() {
        charred = true
    }
}

import XCTest
class SimpleFirewoodTests: XCTestCase {
    func testBurningActuallyChars() {
        let firewood = Firewood()
        firewood.burn()
        assert(firewood.charred, "should be charred after burning")
    }
}

But then of course you cannot press the test button as well Playground is a continuous REPL, so you need to know how to call the tests, does someone know the inside of XCTest to know what to call to do a test run?

Upvotes: 22

Views: 10384

Answers (4)

possen
possen

Reputation: 9266

Here is a full example, which works in Swift 3+, which shows you how to do this. This is nice because now you can use XCTAssert and then they are easily directly moved to your real test bundle once you get the kinks worked out. import XCTest

class MyTestCase: XCTestCase {

   func testExample() {
       print("Test1")
       XCTAssertTrue(true)
   }

   func testAnother() {
       print("Test2")
       XCTAssertFalse(false)
   }
}

MyTestCase.defaultTestSuite().run() // Swift 3
MyTestCase.defaultTestSuite.run() // Swift 4

This is how it will look like:

enter image description here

Unfortunately you have to open the log window to see whether it passed or failed. It would be nice if you could see the test results colorized...

Upvotes: 39

Paul Ardeleanu
Paul Ardeleanu

Reputation: 6700

Running tests in playground now works by invoking run() on the defaultTestSuite of your tests class:

let testSuite = SimpleFirewoodTests.defaultTestSuite()
testSuite.run()

NB: the assert in your test should be replaced with XCTAssertEqual.

Upvotes: 5

Stuart Sharpe
Stuart Sharpe

Reputation: 601

I've just written a blog post explaining how you can do this in Xcode 7, along with a sample Playground which will run Unit Tests. The short answer is, you can create a small test runner object within the playground which runs the tests and reports on the results. Along with an observer to catch failed tests, you can get a pretty good TDD setup with a playground.

http://initwithstyle.net/2015/11/tdd-in-swift-playgrounds/ https://github.com/sshrpe/TDDSwiftPlayground

Upvotes: 13

Rick Ballard
Rick Ballard

Reputation: 4833

XCTest is currently not supported in playgrounds. If this is something that you'd like, I'd encourage you to file a bug report at http://bugreport.apple.com requesting it.

Upvotes: 5

Related Questions