Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add helper methods to XCTestCase unit in Xcode?

Is there a way to add a method to your XCTestCase without it being counted as a test? Something like setUp and tearDown which exists already.

One usecase would be to do a certain operation on an object in some of my test cases at specific points in time, while accessing the instance variables of the class itself (which rolls out the possibility of using static methods and external helper files)

like image 921
Mabedan Avatar asked May 14 '14 17:05

Mabedan


2 Answers

Only methods that start with test will be considered tests. So, just name your helper method something that doesn't start with test.

By the way, I would not be inclined to put XCTAssert statements in your helper method. It works (the appropriate tests will fail), but in some scenarios it makes it hard to decipher which tests caused the assert in the helper method to fire.

like image 88
Rob Avatar answered Oct 17 '22 01:10

Rob


I use what Steve suggested with the optional line parameter in XCTAssert functions so the test failure appears at the callsite and append check instead of test so it isn't recognized as one.

private func checkSunSetsInTheEast(callLine: UInt = #line) {
    XCTFail(callLine: #line)
}

An alternative if you prefer your asserts to be visible in the actual test would be:

func testSun() {
    XCTAssert(sunSetsInEast)
}

private var sunSetsInEast: Bool { return false }

Keeping the test prefix and setting the test to private will stop them being run as tests but XCode's UI will still recognize them as a test so it's probably best to avoid prefixing test at the beginning of helper functions.

like image 33
Declan McKenna Avatar answered Oct 17 '22 00:10

Declan McKenna