2

I have a synchronous function that calls an asynchronous sub function. Now I want to test that the synchronous function sets a property. I've seen many examples of tests using expectations, but since only the sub function is async, I can't set fulfill.

What I would like to do instead is to just do an XCTAssertEqual checking the property to equal a certain value within a given timeout period.

How can this be done?

Here's a sketch:

class TestSubject {
    var noOfCalls = 0

    func funcToTest() {
        Task.init {
            await doSomething()
            await doSomething()
        }
    }

    func doSomething() async {
        ...
        noOfCalls++
    }
}

The test:

func testTestSubject() async {
    var subject = TestSubject()

    subject.funcToTest()

    // this obviously doesn't work because of the async call
    XCTAssertEqual(subject.noOfCalls, 2)
}
G. Marc
  • 4,987
  • 4
  • 32
  • 49
  • did you try use mock? https://www.swiftbysundell.com/articles/mocking-in-swift/ – aiwiguna Feb 25 '22 at 06:22
  • Does this answer your question? [XCTest: Test asyncronous function without completion block](https://stackoverflow.com/questions/33760116/xctest-test-asyncronous-function-without-completion-block) – Cy-4AH Feb 25 '22 at 07:23
  • @Cy-4AH: It's the exact same problem, but the solution involves to change the function under test which I don't want. I'm gonna try write my own XCTAssertEqual function with a timeout argument. It will wait till the expected value becomes available and then check it. – G. Marc Feb 25 '22 at 07:39
  • @G.Marc there is the same problem and solution isn't involving changes in the original function. Assertion is used in expectation timeout handler. – Cy-4AH Feb 25 '22 at 08:56
  • 2
    Did you ever get a good solution for this? – johnny May 12 '22 at 21:12

0 Answers0