2015-11-10 45 views
6

我有用于测试MyApp的UI测试目标。要测试特定的MyApp条件,我需要将UI测试目标的通知发布到MyApp目标。从UI测试目标函数张贴通知我用这:UI测试+ postNotificationName +永远不会到达观察者+ Xcode 7

NSNotificationCenter.defaultCenter().postNotificationName(name, object: nil, userInfo: aUserInfo) 

它看起来这个通知不会到达从UI测试目标观察员,但张贴从MyApp的目标这个通知时,它工作正常。

如何将通知从UI目标发布到MyApp目标?

使用Xcode的7

+0

你打电话,你要听的addObserver?你确定在postNotification之前调用addObserver吗? – picciano

+0

从MyApp目标发布通知可以正常工作,但是从UI测试发布目标dose't时。我也更新了问题。 – Ramis

+1

偏离主题,但发送'self'作为'object'参数是一种很好的做法(或惯例?)。 –

回答

7

也有类似的问题(试图确保NSNotification被张贴某些UI动作之后)。对此进行了小规模的研究。

由于UI测试和应用程序在不同的进程中运行,因此未收到NSNotification。 NSNotification无法通过进程边界,并且NSDistributedNotificationServer在iOS上不可用。因此,目前在UI测试套件和应用程序实例之间没有默认且简单的方式来发布NSNotifications。

但是,有一些方法可以在进程之间进行通信,也可以编写小包装甚至是NSDistributedNotificationCenter iOS代理来进行测试。看看这篇来自Realm的伟大文章:https://academy.realm.io/posts/thomas-goyne-fast-inter-process-communication/

2

我想用UI测试来测试内存泄漏并做到这一点我想在调用视图控制器的deinit的时候在UI测试用例中得到消息。所以,我想出了这个提供IPC机制:

/** 
    Provides simple IPC messaging. To use this class you need to include  
    #include <notify.h> 
    in your bridging header. (Ab)uses UIPasteboard for message delivery, ie. 
    should not be used in production code. 
*/ 
public class SimpleIPC { 
    /// Event notification name for libnotify. 
    private static let notifyEventName = "com.foo.SimpleIPC" 

    /// libnotify token. 
    private var token: Int32 = 0 

    /// Starts listening to the events 
    public func listen(callback: (String? -> Void)) { 
     notify_register_dispatch(SimpleIPC.notifyEventName, &token, dispatch_get_main_queue()) { token in 
      callback(UIPasteboard.generalPasteboard().string) 
     } 
    } 

    public class func send(message: String) { 
     UIPasteboard.generalPasteboard().string = message 
     notify_post(SimpleIPC.notifyEventName) 
    } 

    deinit { 
     notify_cancel(token) 
    } 
} 

它使用的libnotifyUIPasteboard组合的通知+数据传输。可用于单向通信,对于双向通信,可使有效负载包含发件人令牌或使用具有参数化libnotify事件名称的2个实例。

  • 马蒂
+0

2way如何在这里工作?我一直在设置它的问题。发件人令牌究竟是什么? –

0

这是一个Mac应用程序或iOS应用程序?对于Mac应用程序,您可以使用NSDistributedNotificationCenter。

在订阅:

NSDistributedNotificationCenter.defaultCenter().addObserver(object, selector: #selector(ObjectsClass.myFuncWithoutParentheses), name: "uniqueString", object: nil) 

在您的发布者:

NSNotificationCenter.defaultCenter().postNotificationName("uniqueString" object:nil)