Hi folks, I'm writing some tests and I need a wa...
# kotlin-native
o
Hi folks, I'm writing some tests and I need a way to post operations to the main queue and make the test case wait for the queue to be empty before finishing (What I tried to do the the 
sleep
 without success)
Copy code
@Test
fun `This test doesn't execute the println statement`() {
    dispatch_async(dispatch_get_main_queue()) {
        println("dispatch_async")
    }

    NSThread.sleepForTimeInterval(1.0)
}
I'm thinking about something similar to
XCTestExpectation
. Any thoughts?
k
are your tests running on the main thread (sounds like yes)?
o
Yes,
println("$isMainThread")
prints
true
k
so obviously if you block the test you are blocking the main thread
you need to use the run loop
o
That's right, but the run loop doesn't work either
dispatch_main()
throws
Uncaught Kotlin exception: kotlin.native.IncorrectDereferenceException: illegal attempt to access non-shared common.platform.ConcurrencyModelTests.$This test doesn't execute the println statement$lambda-8$FUNCTION_REFERENCE$726@8b6ede08 from other thread
k
yes, you need to freeze anything that you're passing to another thread
o
Copy code
Sorry, but I'm not passing anything

@Test
fun `This test doesn't execute the println statement`() {
    Platform.isMemoryLeakCheckerActive = false

    dispatch_async(dispatch_get_main_queue()) {
        println("dispatch_async")
    }

    dispatch_main()
}
k
sure you are, you're passing the block
o
Sure I was
Copy code
@Test
fun `This test doesn't execute the println statement`() {
    Platform.isMemoryLeakCheckerActive = false

    val block = {
        println("dispatch_async")
    }
    
    dispatch_async(dispatch_get_main_queue(), block.freeze())

    dispatch_main()
}
Now I need a way to stop the loop
k
you can just process the loop until it's empty
i don't recall whether GCD uses the run loop or not
o
Looks like
CFRunLoopRun
and
CFRunLoopStop
could work
k
NSRunLoop would give you a more convenient API
🙏 1
o
Sweet, this works
Copy code
@Test
fun `This test does execute the println statement`() {
    dispatch_async(dispatch_get_main_queue(), {
        println("dispatch_async")
    }.freeze())

    NSRunLoop.currentRunLoop.runUntilDate(NSDate.dateWithTimeInterval(1.0, NSDate.now))
}
Thanks a lot
🍻 2
k
nice