在Swift 3中检查是否在正确的调度队列上 [英] Check if on correct dispatch queue in Swift 3
问题描述
我有一些单元测试,其中我想测试是否在正确的调度队列上调用了回调.
I have a few unit tests in which I'd like to test if a callback is called on the correct dispatch queue.
在Swift 2中,我将当前队列的标签与测试队列进行了比较.但是在Swift 3中,DISPATCH_CURRENT_QUEUE_LABEL
常量不再存在.
In Swift 2, I compared the label of the current queue to my test queue. However in Swift 3 the DISPATCH_CURRENT_QUEUE_LABEL
constant no longer exists.
我确实找到了dispatch_assert_queue
函数.这似乎是我需要的,但是我不确定如何调用它.
I did find the dispatch_assert_queue
function. Which seems to be what I need, but I'm not sure how to call it.
我的Swift 2代码:
My Swift 2 code:
let testQueueLabel = "com.example.my-test-queue"
let testQueue = dispatch_queue_create(testQueueLabel, nil)
let currentQueueLabel = String(UTF8String: dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL))!
XCTAssertEqual(currentQueueLabel, testQueueLabel, "callback should be called on specified queue")
更新:
我对缺乏自动完成功能感到困惑,但是可以使用__dispatch_assert_queue
:
I got confused by the lack of autocomplete, but it is possible to use __dispatch_assert_queue
:
if #available(iOS 10.0, *) {
__dispatch_assert_queue(test1Queue)
}
虽然这对单元测试有效,但它烦人地使用EXC_BAD_INSTRUCTION
停止了整个过程,而不是仅使测试失败.
While this does work for unit tests, it annoyingly stops the whole process with a EXC_BAD_INSTRUCTION
instead of only failing a test.
推荐答案
回答我自己的问题:
基于 KFDoom的评论,我现在正在使用setSpecific
和getSpecific
.
Based on KFDoom's comments, I'm now using setSpecific
and getSpecific
.
这将创建一个密钥,将其设置在测试队列中,然后再次获取它:
This creates a key, sets it on the test queue, and later on, gets it again:
let testQueueLabel = "com.example.my-test-queue"
let testQueue = DispatchQueue(label: testQueueLabel, attributes: [])
let testQueueKey = DispatchSpecificKey<Void>()
testQueue.setSpecific(key: testQueueKey, value: ())
// ... later on, to test:
XCTAssertNotNil(DispatchQueue.getSpecific(key: testQueueKey), "callback should be called on specified queue")
请注意,键没有任何关联的值(其类型为Void
),我只对特定项的存在感兴趣,而不对它的值感兴趣.
Note that there's no value associated with the key (its type is Void
), I'm only interested in the existence of the specific, not in it's value.
重要!
使用完密钥后,请确保保留对密钥的引用或清除.否则,新创建的密钥可能会使用相同的内存地址,从而导致异常行为.请参阅: http://tom.lokhorst.eu/2018/02/在发送队列中迅速泄漏抽象
Important!
Make sure to keep a reference to the key, or cleanup after you're done using it. Otherwise a newly created key could use the same memory address, leading to weird behaviour. See: http://tom.lokhorst.eu/2018/02/leaky-abstractions-in-swift-with-dispatchqueue
这篇关于在Swift 3中检查是否在正确的调度队列上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!