How to Unit Test an App Extension on Xcode 6

How to unit test an app extension on Xcode 6

I have reported the bug to Apple. And sadly, the answer is that the keyboard extension is not support unit test now. The answer comes from Apple:

  • It's not currently supported to run unit tests inside an app extension
  • Instead, factor the code you want to test into a framework and test the code there
  • Link the framework into your extension

Testing iOS Keyboard App Extension

After asking to Apple Developpers, the answer is no.
There is no way to do UITesting for Keyboard Extensions for now.

Writing a unit-test for a class extension in Swift

As @dan alluded to, you need to call it from an instance of the UIViewController. Usually you don't want to instantiate framework objects in your tests if you can avoid it, so here are some options to avoid that:

  1. Make presentAlert static so that you can just UIViewController.presentAlert
  2. Make presentAlert a free function (don't put it in the extension)
  3. Extend a protocol instead – I think this is the cleanest option

protocol Presentable {}

extension Presentable {
func presentAlert(title: String, message : String) { /* ... */ }
}

Then, whenever you need it you can extension UIViewController: Presentable {}. And in your tests, you can just use a dummy class. The added benefit with this approach is that you can reuse that function on any type if needed, without globally exposing it when you don't.

Addendum

When we extend the protocol we are saying "anything that implements this protocol will get this method for free." The trick here is that this protocol is empty and, therefore, very easy to "implement."

extension YourViewController: Presentable {}

How to take iOS Framework testing target and run it in a dummy app?

Ah, this article helped:

https://medium.com/@ryuichi/setup-host-app-for-keychain-tests-in-xcode-8-97222611917e#.z3zpqwnzt

I was adding a totally new app project, I just needed to add a new Target in the Framework project for a Single View Application

That then allows me to select Host Application in the testing target.

Using my previous diagram, the final result that worked is:

Framework Project
|
|- Unit Test Target
|- Framework Target
|- Dummy App Target

Sample Image



Related Topics



Leave a reply



Submit