Skip to content

Commit

Permalink
Refactor FileLastForecastCoroutinesStoreTest
Browse files Browse the repository at this point in the history
The setDispatcherAndRunTest method was unnecessary because I could pass
testDispatcher to runTest.
  • Loading branch information
tobyhs committed Aug 26, 2024
1 parent 96e39c5 commit d7f9b0e
Showing 1 changed file with 5 additions and 13 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import io.github.tobyhs.weatherweight.di.AppModule
import io.github.tobyhs.weatherweight.test.ForecastSearchFactory

import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.TestDispatcher
import kotlinx.coroutines.test.runTest

import org.hamcrest.CoreMatchers.equalTo
Expand All @@ -19,35 +18,28 @@ import java.io.File
class FileLastForecastCoroutinesStoreTest {
private val directory = File("/tmp")
private val moshi = AppModule().provideMoshi()
private lateinit var testDispatcher: TestDispatcher
private val store by lazy { FileLastForecastCoroutinesStore(directory, moshi, testDispatcher) }
private val testDispatcher = StandardTestDispatcher()
private val store = FileLastForecastCoroutinesStore(directory, moshi, testDispatcher)
private val forecastSearchAdapter by lazy { moshi.adapter(ForecastSearch::class.java) }
private val file = File(directory, "lastForecast.json")
private val forecastSearch by lazy { ForecastSearchFactory.create() }

@Test
fun `get when file does not exist`() = setDispatcherAndRunTest {
fun `get when file does not exist`() = runTest(testDispatcher) {
file.delete()
assertThat(store.get(), nullValue())
}

@Test
fun `get when file exists`() = setDispatcherAndRunTest {
fun `get when file exists`() = runTest(testDispatcher) {
file.writeText(forecastSearchAdapter.toJson(forecastSearch))
assertThat(store.get(), equalTo(forecastSearch))
}

@Test
fun save() = setDispatcherAndRunTest {
fun save() = runTest(testDispatcher) {
file.delete()
store.save(forecastSearch)
assertThat(forecastSearchAdapter.fromJson(file.readText()), equalTo(forecastSearch))
}

private fun setDispatcherAndRunTest(testBody: suspend () -> Unit) {
runTest {
this@FileLastForecastCoroutinesStoreTest.testDispatcher = StandardTestDispatcher(testScheduler)
testBody()
}
}
}

0 comments on commit d7f9b0e

Please sign in to comment.