KamilH
11/08/2023, 2:01 PMsuspend fun <T> execute(work: suspend Scope.() -> T): Result<T> =
Result.runCatching {
scope.work()
}
in the test, I would like to mock Scope
(full example in the thread)KamilH
11/08/2023, 2:02 PMclass Executor {
private val scope: Scope = Scope()
suspend fun <T> execute(work: suspend Scope.() -> T): Result<T> =
Result.runCatching {
scope.work()
}
class Scope {
val key: String = "key"
val api: Api = object : Api {
override fun get(key: String): String = "value with $key"
}
}
}
interface Api {
fun get(key: String): String
}
class Repository(private val executor: Executor) {
suspend fun getString(): Result<String> =
executor.execute {
api.get(key)
}
}
Test:
class RepositoryTest {
private val executor: Executor = mockk()
private val repository = Repository(executor)
@Test
fun `repository returns value`() = runTest {
// mock Scope
val result = repository.getString()
assert(result.isSuccess)
}
}
Klitos Kyriacou
11/08/2023, 2:43 PMKamilH
11/08/2023, 2:51 PMScope
has a few fields that come from other classes that are injected. I would like to test whether Scope
returns correct values separately and then usage of execute
separately