Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 736
Raymond Avatar asked Apr 23 '15 11:04

Raymond


People also ask

How do I run XCTest?

To run your app's XCTests on Test Lab devices, build it for testing on a Generic iOS Device: From the device dropdown at the top of your Xcode workspace window, select Generic iOS Device. In the macOS menu bar, select Product > Build For > Testing.

Where will you use setUp and teardown methods and make it run once for all the test in the class?

Discussion. As outlined in Recipe 4.6, JUnit calls setUp( ) before each test, and tearDown( ) after each test. In some cases you might want to call a special setup method once before a series of tests, and then call a teardown method once after all tests are complete.

Where will you use setUp () and teardown () methods?

Prepare and Tear Down State for a Test Class XCTest runs setUp() once before the test class begins. If you need to clean up temporary files or capture any data that you want to analyze after the test class is complete, use the tearDown() class method on XCTestCase .

Which function can you use on XCTest to cleanup after every unit test?

Use these blocks to tear down state and clean up resources after a specific test method. XCTest runs the teardown methods once after each test method completes, with tearDown() first, then tearDownWithError() , then tearDown() async throws . Use these methods to tear down state after each test method.


2 Answers

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:

  1. 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
  2. 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: Declaring the PrincipalClass in Info.plist

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.

like image 148
Jan Nash Avatar answered Sep 22 '22 08:09

Jan Nash


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() } 
like image 38
Martin R Avatar answered Sep 24 '22 08:09

Martin R