I'm wondering if there is a way to use unit when XCtesting in order to specify a constant variable that isn't torn down between separate test cases? I realize that generally best practices for unit testing are to keep the tests as self contained as possible but in my current situation it would make the tests execute a lot faster if I were able to do this and keep a constant variable between test cases.
Currently, any type of init function that I call
override init() {
super.init()
}
Leaves me with an EXC_BAD_INSTRUCTION error. If I can't use init() in XCTestCase, is there another work around that I can use?
Try moving the variable outside of the XCTestCase
class.
import XCTest
var counter = 0 // Note this is outside the class declaration
class MyTests: XCTestCase {
override func setUp() {
super.setUp()
counter++
print("Counter: \(counter)")
}
func testOne() {
...
}
func testTwo() {
...
}
func testThree() {
...
}
}
This gives an output like this.
...
Counter: 1
...
Counter: 2
...
Counter: 3
...
You can use the class setUp
and tearDown
methods for exactly this purpose. The class setUp
method is called once before the first test method begins and the class tearDown
method is called once after all test methods have completed.
My understanding is that these are intended precisely for handling the kind of test-wide state you describe. Apple has some good documentation on it.
The advantage of this approach is that the state is at least kept local to the test class, if not the individual tests.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.