Skip to content

Commit f8687d1

Browse files
authored
fix: Improve flaky tests at SentryDispatchQueueWrapperSwiftTests (#6383)
* fix: Improve flaky tests at SentryDispatchQueueWrapperSwiftTests * Improve tests
1 parent 647a6f5 commit f8687d1

File tree

1 file changed

+26
-17
lines changed

1 file changed

+26
-17
lines changed

Tests/SentryTests/Networking/SentryDispatchQueueWrapperTests.swift

Lines changed: 26 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -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

Comments
 (0)