How to run one-time setup code before executing any XCTest
I have the following problem. I want to execute a piece of code before all test classes are executed. For instance: I don't want my game to use the SoundEngine singleton during executing, but the SilentSoundEngine. I would like to activate the SilentSoundEngine one time not in all tests. All my tests look like this:
class TestBasketExcercise : XCTestCase {
override func setUp() {
SilentSoundEngine.activate () // SoundEngine is a singleton
}
// The tests
}
-Edit- Most of the answers are directed at providing custom superclass for the TestCase. I am looking for a more general and cleaner way to provide the environment that all tests need to execute. Isn't there a "main" function/ Appdelegate like feature somewhere for tests?
Solution 1:
TL;DR:
As stated here, you should declare an NSPrincipalClass in your test-targets Info.plist. Execute all the one-time-setup code inside the init of this class, since "XCTest automatically creates a single instance of that class when the test bundle is loaded", thus all your one-time-setup code will be executed once when loading the test-bundle.
A bit more verbose:
To answer the idea in your edit first:
Afaik, there is no main()
for the test bundle, since the tests are injected into your running main target, therefore you would have to add the one-time-setup code into the main()
of your main target with a compile-time (or at least a runtime) check if the target is used to run tests. Without this check, you'd risk activating the SilentSoundEngine
when running the target normally, which I guess is undesirable, since the class name implies that this sound-engine will produce no sound and honestly, who wants that? :)
There is however an AppDelegate
-like feature, I will come to that at the end of my answer (if you're impatient, it's under the header "Another (more XCTest-specific) approach").
Now, let's divide this question into two core problems:
- How can you ensure that the code you want to execute exactly one time when running the tests is actually being executed exactly one time when running the tests
- Where should you execute that code, so it doesn't feel like an ugly hack and so it just works without you having to think of it and remember necessary steps each time you write a new test suite
Regarding point 1:
As @Martin R mentioned correctly in his comments to this answer to your question, overriding +load
is not possible anymore as of Swift 1.2 (which is ancient history by now :D), and dispatch_once()
isn't available anymore in Swift 3.
One approach
When you try to use dispatch_once
anyway, Xcode (>=8) is as always very smart and suggests that you should use lazily initialized globals instead.
Of course, the term global
tends to have everyone indulge in fear and panic, but you can of course limit their scope by making them private/fileprivate (which does the same for file-level declarations), so you don't pollute your namespace.
Imho, they are actually a pretty nice pattern (still, the dose makes the poison...) that can look like this, for example:
private let _doSomethingOneTimeThatDoesNotReturnAResult: Void = {
print("This will be done one time. It doesn't return a result.")
}()
private let _doSomethingOneTimeThatDoesReturnAResult: String = {
print("This will be done one time. It returns a result.")
return "result"
}()
for i in 0...5 {
print(i)
_doSomethingOneTimeThatDoesNotReturnAResult
print(_doSomethingOneTimeThatDoesReturnAResult)
}
This prints:
This will be done one time. It doesn't return a result.
This will be done one time. It returns a result.
0
result
1
result
2
result
3
result
4
result
5
result
Side note:
Interestingly enough, the private lets are evaluated before the loop even starts, which you can see because if it were not the case, the 0 would have been the very first print. When you comment the loop out, it will still print the first two lines (i.e. evaluate the lets).
However, I guess that this is playground specific behaviour because as stated here and here, globals are normally initialized the first time they are referenced somewhere, thus they shouldn't be evaluated when you comment out the loop.
Another (more XCTest-specific) approach
(This actually solves both point 1 and 2...)
As the company from Cupertino states here, there is a way to run one-time-pre-testing setup code.
To achieve this, you create a dummy setup-class (maybe call it TestSetup?) and put all the one time setup code into its init:
class TestSetup: NSObject {
override init() {
SilentSoundEngine.activate()
}
}
Note that the class has to inherit from NSObject, since Xcode tries to instantiate the "single instance of that class" by using +new
, so if the class is a pure Swift class, this will happen:
*** NSForwarding: warning: object 0x11c2d01e0 of class 'YourTestTargetsName.TestSetup' does not implement methodSignatureForSelector: -- trouble ahead
Unrecognized selector +[YourTestTargetsName.TestSetup new]
Then, you declare this class as the PrincipalClass in your test-bundles Info.plist file:
Note that you have to use the fully qualified class-name (i.e. YourTestTargetsName.TestSetup as compared to just TestSetup), so the class is found by Xcode (Thanks, zneak...).
As stated in the documentation of XCTestObservationCenter, "XCTest automatically creates a single instance of that class when the test bundle is loaded", so all your one-time-setup code will be executed in the init of TestSetup when loading the test-bundle.
Solution 2:
From Writing Test Classes and Methods:
You can optionally add customized methods for class setup
(+ (void)setUp)
and teardown(+ (void)tearDown)
as well, which run before and after all of the test methods in the class.
In Swift that would be class
methods:
override class func setUp() {
super.setUp()
// Called once before all tests are run
}
override class func tearDown() {
// Called once after all tests are run
super.tearDown()
}
Solution 3:
If you want to call the setUp
method only once for all UI Tests in the class, in Xcode 11 you can call override class func setUp()
This approach is part of Apple documentation for UI testing: https://developer.apple.com/documentation/xctest/xctestcase/understanding_setup_and_teardown_for_test_methods
Solution 4:
If you build a superclass for your test case to be based on, then you can run a universal setup in the superclass and do whatever specific setup you might need to in the subclasses. I'm more familiar with Obj-C than Swift and haven't had a chance to test this yet, but this should be close.
// superclass
class SuperClass : XCTestCase {
override func setUp() {
SilentSoundEngine.activate () // SoundEngine is a singleton
}
}
// subclass
class Subclass : Superclass {
override func setUp() {
super.setup()
}
}