swift - 无法在 Swift 中从 XCTest 打开 NSStream

标签 swift foundation xctest nsstream

我正在尝试编写一个测试套接字连接的 XCTest。这是我的连接代码大致的样子:

public class MyConnection: NSObject, NSStreamDelegate {
  private let queue = NSOperationQueue()
  private var inputStream: NSInputStream!
  private var outputStream: NSOutputStream!

  public func connect() {
    println("Attempting to connect")
    queue.addOperationWithBlock() {
      var readStream: Unmanaged<CFReadStream>?
      var writeStream: Unmanaged<CFWriteStream>?
      CFStreamCreatePairWithSocketToHost(nil,
                                         "[my ip address]",
                                         8333,
                                         &readStream,
                                         &writeStream);
      if readStream == nil || writeStream == nil {
        println("Connection failed")
        return
      }
      self.inputStream = readStream!.takeUnretainedValue()
      self.outputStream = writeStream!.takeUnretainedValue()
      self.inputStream.delegate = self
      self.outputStream.delegate = self
      self.inputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode:NSDefaultRunLoopMode)
      self.outputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode:NSDefaultRunLoopMode)
      self.inputStream.open()
      self.outputStream.open()
    }
  }

  // MARK: - NSStreamDelegate

  public func stream(stream: NSStream!, handleEvent event: NSStreamEvent) {
    println("THIS NEVER GETS CALLED!")
    // Notifies delegate that connection opened.
  }
}

我编写的 XCTestCase 基本上只是调用 connect() 方法,并在连接成功后等待调用委托(delegate)方法。但是,永远不会调用委托(delegate)方法。我需要做一些特别的事情才能在我的测试中工作吗?

最佳答案

这在我的单元测试中失败的事实是转移注意力。由于 NSOperationQueue 的工作方式,此代码不起作用。队列动态地创建和销毁线程。所以我在运行循环上为一个生命周期很短的线程安排我的流。因此,我的回调从未被调用,因为运行循环被破坏了。

正确的解决方案是直接创建一个 NSThread 并使用该线程的运行循环而不是尝试使用队列。

关于swift - 无法在 Swift 中从 XCTest 打开 NSStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25397357/

相关文章:

ios 快速应用程序开发 : UIScrollview not scrolling contents and working properly

swift - 在 Swift 中如何测试索引是否超出范围?

ios - Xcode UI 测试 : how to identify a custom view with no static text?

json - 将序列化的 JSON 加载到表中?

ios - 在 Swift iOS 中未调用 Google Places 回调

ios - 如何旋转方向?

objective-c - 如何在ARC下自动释放未返回的对象

ios - 通过 NSStream 判断连接建立成功和连接断开

objective-c - [NSObject 描述]

objective-c - 为什么当我测试一个方法抛出异常并且该方法抛出异常时,测试会停止?