这些同步方法如何进行有效的单元测试?

时间:2016-01-28 13:31:49

标签: multithreading swift unit-testing synchronization

根据this question的答案,我对以下两种同步方法的简单易用性感到满意:

func synchronized(lock: AnyObject, closure: () -> Void) {
    objc_sync_enter(lock)
    closure()
    objc_sync_exit(lock)
}

func synchronized<T>(lock: AnyObject, closure: () -> T) -> T {
    objc_sync_enter(lock)
    defer { objc_sync_exit(lock) }
    return closure()
}

但是为了确保他们实际上正在做我想做的事情,我想把它们包装成一堆单元测试。如何编写有效测试这些方法的单元测试(并显示它们实际上正在同步代码)?

理想情况下,我也希望这些单元测试尽可能简单明了。据推测,此测试应该是代码,如果在同步块之外运行,将提供一组结果,但在这些同步块内提供完全独立的结果集。

1 个答案:

答案 0 :(得分:1)

这是一个可运行的XCTest,用于验证同步。如果你同步delayedAddToArray,它将起作用,否则它将失败。

class DelayedArray:NSObject {
    func synchronized(lock: AnyObject, closure: () -> Void) {
        objc_sync_enter(lock)
        closure()
        objc_sync_exit(lock)
    }

    private var array = [String]()
    func delayedAddToArray(expectation:XCTestExpectation) {
        synchronized(self) {
            let arrayCount = self.array.count
            self.array.append("hi")
            sleep(5)
            XCTAssert(self.array.count == arrayCount + 1)
            expectation.fulfill()
        }
    }
}

func testExample() {
    let expectation = self.expectationWithDescription("desc")
    let expectation2 = self.expectationWithDescription("desc2")

    let delayedArray:DelayedArray = DelayedArray()
    // This is an example of a functional test case.
    let thread = NSThread(target: delayedArray, selector: "delayedAddToArray:", object: expectation)
    let secondThread = NSThread(target: delayedArray, selector: "delayedAddToArray:", object: expectation2)
    thread.start()
    sleep(1)
    secondThread.start()

    self.waitForExpectationsWithTimeout(15, handler: nil)
}