diff --git a/app/src/test/java/com/juandgaines/testground/presentation/ProfileViewModelTest.kt b/app/src/test/java/com/juandgaines/testground/presentation/ProfileViewModelTest.kt index 4c0f5d5..322cea0 100644 --- a/app/src/test/java/com/juandgaines/testground/presentation/ProfileViewModelTest.kt +++ b/app/src/test/java/com/juandgaines/testground/presentation/ProfileViewModelTest.kt @@ -8,6 +8,7 @@ import com.juandgaines.testground.domain.Place import com.juandgaines.testground.domain.Profile import com.juandgaines.testground.domain.User import com.juandgaines.testground.domain.UserRepository +import com.juandgaines.testground.util.MainDispatcherRule import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.StandardTestDispatcher @@ -24,14 +25,15 @@ import java.util.UUID @OptIn(ExperimentalCoroutinesApi::class) class ProfileViewModelTest { - private val testDispatcher = StandardTestDispatcher() + @get:Rule + val testDispatcher = MainDispatcherRule() private lateinit var viewModel: ProfileViewModel private lateinit var repository: UserRepositoryFake @Before fun setUp() { - Dispatchers.setMain(testDispatcher) + repository = UserRepositoryFake() viewModel = ProfileViewModel( @@ -44,11 +46,6 @@ class ProfileViewModelTest { ) } - @After - fun tearDown() { - Dispatchers.resetMain() - } - @Test fun givenValidUserId_whenLoadProfile_thenProfileIsLoaded() = runTest { // Act diff --git a/app/src/test/java/com/juandgaines/testground/util/MainDispatcherRule.kt b/app/src/test/java/com/juandgaines/testground/util/MainDispatcherRule.kt new file mode 100644 index 0000000..9447bac --- /dev/null +++ b/app/src/test/java/com/juandgaines/testground/util/MainDispatcherRule.kt @@ -0,0 +1,23 @@ +package com.juandgaines.testground.util + +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.TestDispatcher +import kotlinx.coroutines.test.UnconfinedTestDispatcher +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.setMain +import org.junit.rules.TestWatcher +import org.junit.runner.Description + +@OptIn(ExperimentalCoroutinesApi::class) +class MainDispatcherRule( + private val testDispatcher: TestDispatcher = UnconfinedTestDispatcher() +) : TestWatcher() { + override fun starting(description: Description) { + Dispatchers.setMain(testDispatcher) + } + + override fun finished(description: Description) { + Dispatchers.resetMain() + } +} \ No newline at end of file