@@ -30,42 +30,51 @@ class SentryDispatchQueueWrapperSwiftTests: XCTestCase {
3030 }
3131
3232 func testDispatchAsyncOnMainQueueIfNotMainThreadOnMain( ) {
33- let expectation = XCTestExpectation ( )
33+ let blockExpectation = XCTestExpectation ( description : " Block Expectation " )
3434
35- var flag = false
35+ let outerExpectation = XCTestExpectation ( description: " This exepctation should execute last " )
36+ outerExpectation. isInverted = true
3637
3738 let sut = SentryDispatchQueueWrapper ( )
3839 sut. dispatchAsyncOnMainQueueIfNotMainThread {
3940 XCTAssertTrue ( Thread . isMainThread)
40- XCTAssertFalse ( flag , " Block did not run synchronously " )
41+ self . wait ( for : [ outerExpectation ] , timeout : 1 )
4142
42- expectation . fulfill ( )
43+ blockExpectation . fulfill ( )
4344 }
44- flag = true
45+ outerExpectation . fulfill ( )
4546
46- wait ( for: [ expectation ] , timeout: 2 )
47+ wait ( for: [ blockExpectation ] , timeout: 2 )
4748 }
4849
4950 func testDispatchAsyncOnMainQueueIfNotMainThreadFromBackground( ) {
5051 let expectation = XCTestExpectation ( )
5152
5253 DispatchQueue . global ( ) . async {
53- let innerExpectation = XCTestExpectation ( description: " Expectation on background thread " )
54-
55- var flag = false
54+ let mainThreadExpectation = XCTestExpectation ( description: " Main Thread Expectation " )
55+ let bgThreadExpectation = XCTestExpectation ( description : " BG Thread Expectation " )
56+
5657 let sut = SentryDispatchQueueWrapper ( )
58+
5759 sut. dispatchAsyncOnMainQueueIfNotMainThread {
58- XCTAssertTrue ( Thread . isMainThread)
59- XCTAssertTrue ( flag, " Block did not run asynchronously " )
60-
61- innerExpectation. fulfill ( )
60+ XCTAssertTrue ( Thread . isMainThread, " The block didn't run on the main thread, but it should have " )
61+
62+ // Wait for the background thread to fulfill its expectation
63+ // If this code runs on the same thread as the bgThreadExpectation, the expectation times out.
64+ self . wait ( for: [ bgThreadExpectation] , timeout: 5.0 )
65+
66+ // Unblock the BG thread
67+ mainThreadExpectation. fulfill ( )
6268 }
63- flag = true
64-
65- self . wait ( for: [ innerExpectation] , timeout: 2 )
69+
70+ // Unblock the main thread
71+ bgThreadExpectation. fulfill ( )
72+
73+ self . wait ( for: [ mainThreadExpectation] , timeout: 5.0 )
74+
6675 expectation. fulfill ( )
6776 }
6877
69- wait ( for: [ expectation] , timeout: 2 )
78+ wait ( for: [ expectation] , timeout: 10.0 )
7079 }
7180}
0 commit comments