How can these synchronization methods be tested effectively?

Based on the answers to this question , I am pleased with the simplicity and ease of use of the following two synchronization methods:

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() } 

But to be sure that they really do what I want, I want to wrap them in heaps of unit tests. How can I write unit tests that will effectively test these methods (and show that they actually synchronize the code)?

Ideally, I would like these unit tests to be as simple and clear as possible. Presumably, this test should be a code that, if executed outside the synchronization block, will give one set of results, but will give a completely separate set of results inside these synchronized blocks.

+5
source share
1 answer

Here is the XCTest run that checks for synchronization. If you synchronize delayedAddToArray, it will work, otherwise it will fail.

 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) } 
+1
source

Source: https://habr.com/ru/post/1241718/


All Articles