Swift: overriding an initializer that accepts NSInvocation

I'm trying to create a reusable test harness in Swift with the idea that subclasses will extend the test harness to provide the test instance and can add their own subclass testing methods, something like this:

class FooTestHarness: XCTestCase { let instance: Foo init(instance: Foo) { self.instance = instance } func testFooBehavior() { XCTAssert(instance.doesFoo()) } } class FooPrime: Foo { func doesFooPrime(): Bool { /* ... */ } } class FooPrimeTests: XCTestCase { init() { super.init(FooPrime()) } func myInstance(): FooPrime { return instance as FooPrime } func testFooPrimeBehavior() { XCTAssert(myInstance().doesFooPrime()) } } 

However, when Xcode testrunner tries to run FooPrimeTests , it does not call no-arg init() , it calls init(invocation: NSInvocation!) (And fails because it does not). I tried to override this in FooTestHarness :

  init(invocation: NSInvocation!, instance: Foo) { self.instance = instance super.init(invocation) } 

and FooPrimeTests :

  init(invocation: NSInvocation!) { super.init(invocation, FooPrime()) } 

but this fails with the message 'NSInvocation' is unavailable .

Is there any workaround?

+8
swift nsinvocation
source share
1 answer

I'm not sure if I understood correctly, but by checking the code that you suggested, you should get a compiler. Mistake: enter image description here

Which, in fact, I think is quite normal, since your FooPrimeTests are just subclasses of XCTestCase that have different init, such as:

 init!(invocation: NSInvocation!) init!(selector: Selector) init() 

It is likely that when you send a message, you doubt that you are using an older version of Swift (I am currently running it on beta version of Xcode 6.2), so you cannot see this error. But, and I say again, if I understood correctly, your FooPrimeTests class cannot see your custom initializer just because it loads XCTestCase, not FooTestHarness. What is the class in which init(instance: Foo) defined.

Thus, you might want to define FooPrimeTests as a subclass of FooTestHarness. Therefore, you should be able to correctly see your initializer. I hope for this help.

+1
source share

All Articles