gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 08:06:51 26 4
gpt4 key购买 nike

基于对 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()
}

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

理想情况下,我还希望这些单元测试尽可能简单明了。据推测,这个测试应该是这样的代码,如果在同步块(synchronized block)之外运行,将给出一组结果,但在这些同步块(synchronized block)内给出一组完全独立的结果。

最佳答案

这是一个可运行的 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)
}

关于multithreading - 如何对这些同步方法进行有效的单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35062921/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com