Skip to content

Use the TestCoroutineDispatcher from Dispatchers.Main by default #3006

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged

Conversation

dkhalanskyjb
Copy link
Collaborator

@dkhalanskyjb dkhalanskyjb commented Oct 29, 2021

This change eliminates the common pattern that is currently needed to be able to use Dispatchers.Main in code under test:

val dispatcher = TestCoroutineDispatcher()
val scope = TestCoroutineScope(dispatcher)

@BeforeTest
fun setMain() {
  Dispatchers.setMain(dispatcher)
}

@AfterTest
fun resetMain() {
  Dispatcher.resetMain()
  scope.cleanupTestCoroutines()
}

@Test
fun testFoo() = scope.runBlockingTest { ... }

Now this becomes just

@BeforeTest
fun setMain() {
  Dispatchers.setMain(TestCoroutineDispatcher())
}

@AfterTest
fun resetMain() {
  Dispatcher.resetMain()
}

@Test
fun testFoo() = runTest { ... }

This is done by querying Dispatchers.Main for its TestCoroutineScheduler.

@dkhalanskyjb dkhalanskyjb requested a review from qwwdfsad October 29, 2021 12:37
@dkhalanskyjb dkhalanskyjb force-pushed the coroutines-test-coroutineScope branch from 8b43bd8 to d0913ab Compare October 29, 2021 12:39
Copy link
Collaborator

@qwwdfsad qwwdfsad left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔥

@dkhalanskyjb dkhalanskyjb force-pushed the coroutines-test-exception-handling branch from 9e5e8f8 to 9f635e9 Compare November 1, 2021 13:53
Base automatically changed from coroutines-test-exception-handling to coroutines-test-virtualtime November 1, 2021 13:57
@dkhalanskyjb dkhalanskyjb force-pushed the coroutines-test-coroutineScope branch from d0913ab to 31636fe Compare November 1, 2021 13:58
@dkhalanskyjb dkhalanskyjb merged commit 37a8cea into coroutines-test-virtualtime Nov 1, 2021
@dkhalanskyjb dkhalanskyjb deleted the coroutines-test-coroutineScope branch November 1, 2021 13:59
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants