Skip to content

Instantly share code, notes, and snippets.

@robertmryan
Created October 26, 2019 23:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robertmryan/8989dade9c5bef9ac0db75040d65f747 to your computer and use it in GitHub Desktop.
Save robertmryan/8989dade9c5bef9ac0db75040d65f747 to your computer and use it in GitHub Desktop.
class MyAppTests: XCTestCase {
func testIets() {
let expectation = self.expectation(description: "doSomething")
AsyncClass().doSomething {
expectation.fulfill()
}
wait(for: [expectation], timeout: 5)
}
}
class AsyncClass {
func doSomething(completion: @escaping () -> Void) {
let group = DispatchGroup()
for _ in 0...5 {
group.enter()
DispatchQueue.global().async {
Thread.sleep(forTimeInterval: 1)
group.leave()
}
}
group.notify(queue: .main) {
completion()
}
}
}
@robertmryan
Copy link
Author

robertmryan commented Oct 26, 2019

It strikes me that the expectation code shown above is just as concise and intuitive as your original code snippet (shown below), and it doesn’t require any changes to your doSomething method:

func testIets() {
    let clazz = AsyncClass()

    var isCalled = false

    clazz.doSomething {
        isCalled = true
    }

    XCTAssert(isCalled)
}

@Jasperav
Copy link

Jasperav commented Oct 27, 2019

In the end, I just wanted this:

func testIets() {
    var isCalled = false
    AsyncClass().doSomething()
    var isCalled = true

    XCTAssert(isCalled)
}

(ofcourse without the boolean isCalled). If you haven't seen it, I implemented this behavior: https://stackoverflow.com/a/58576029/7715250. As I explained it inside many comments, I want to fill my database with random data. Thats expensive CPU operation, so I want to dispatch it to all available threads, so not only the calling thread. I also want it sync, because I don't want to deal all the time with all the expectations and closures. If there is a better way, I would like to see how :)

@robertmryan
Copy link
Author

robertmryan commented Oct 28, 2019

@Jasperav - IMHO, it’s not advisable to introduce anti-patterns into one's codebase solely for the sake of testing, when the testing framework already provides a nice, concise mechanism to test these scenarios.

My suggestion is that you do not add blocking/synchronous methods to your code base, and instead use expectations when testing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment