What is a proper way to mock the receiver with whi...
# mockk
k
What is a proper way to mock the receiver with which lambda is being called?
Copy code
suspend 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)
Copy code
class 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:
Copy code
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)
    }
}
k
You should pass a Scope to the Executor constructor (dependency injection).
k
The thing is that in the real app,
Scope
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