Coroutine testing

The runBlocking coroutine builder can be used for testing. This creates a coroutine that uses a current thread. The test within the JUnit framework may look as follows:

class ExampleUnitTest {

@Test
fun comicLoading() = runBlocking {
val image = async { loadImage() }.await()
assertNotNull(image)
}
}

This snippet loads an image using the async coroutine builder, and checks that the image is not null. The source code of the runBlocking function looks as follows:

@Throws(InterruptedException::class)
public fun <T> runBlocking(context: CoroutineContext = EmptyCoroutineContext, block: suspend CoroutineScope.() -> T): T {
val currentThread = Thread.currentThread()
val contextInterceptor = context[ContinuationInterceptor]
val privateEventLoop = contextInterceptor == null // create private event loop if no dispatcher is specified
val eventLoop = if (privateEventLoop) BlockingEventLoop(currentThread) else contextInterceptor as? EventLoop
val newContext = GlobalScope.newCoroutineContext(
if (privateEventLoop) context + (eventLoop as ContinuationInterceptor) else context
)
val coroutine = BlockingCoroutine<T>(newContext, currentThread, eventLoop, privateEventLoop)
coroutine.start(CoroutineStart.DEFAULT, coroutine, block)
return coroutine.joinBlocking()
}

As you can see, the runBlocking coroutine builder uses the currentThread function to obtain an instance of the Thread class. When you run this test, you will see the following window:

This window shows that the test has passed successfully.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.146.35.72