Skip to content

Instantly share code, notes, and snippets.

@apelsoczi
Created July 28, 2022 08:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save apelsoczi/497a8f002d78da0bb5121b94755b868c to your computer and use it in GitHub Desktop.
Save apelsoczi/497a8f002d78da0bb5121b94755b868c to your computer and use it in GitHub Desktop.
import android.util.Log
import com.novonordisk.shared.MainCoroutineRule
import io.mockk.every
import io.mockk.mockkStatic
import io.mockk.unmockkAll
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.test.runTest
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
class CoroutineUseCaseTest {
// Overrides Dispatchers.Main used in Coroutines
@get:Rule
var coroutineRule = MainCoroutineRule()
private val testDispatcher = coroutineRule.testDispatcher
@Before
fun setUp() {
mockkStatic(Log::class)
every { Log.d(any(), any()) } returns 0
}
@After
fun teardown() {
unmockkAll()
}
@Test
fun `UseCase exception returns failure`() = runTest {
val useCase = ExceptionUseCase(testDispatcher)
val result = useCase(Unit)
assert(result.isFailure)
}
private class ExceptionUseCase(dispatcher: CoroutineDispatcher) : UseCase<Unit, Unit>(dispatcher) {
override suspend fun execute(parameters: Unit) {
throw Exception("Test exception")
}
}
}
import android.util.Log
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.withContext
/**
* Executes business logic synchronously or asynchronously using Coroutines.
*/
abstract class UseCase<in P, R>(private val coroutineDispatcher: CoroutineDispatcher) {
internal open val TAG: String = "UseCase"
/** Executes the use case asynchronously and returns a [Result].
*
* @return a [Result].
*
* @param params the input parameters to run the use case with
*/
suspend operator fun invoke(params: P): Result<R> {
return try {
// Moving all use case's executions to the injected dispatcher
// In production code, this is usually the Default dispatcher (background thread)
// In tests, this becomes a TestCoroutineDispatcher
withContext(coroutineDispatcher) {
execute(params).let {
Result.success(it)
}
}
} catch (e: Exception) {
Log.d(TAG, "invoke: ", e)
Result.failure(e)
}
}
/**
* Override this to set the code to be executed.
*/
@Throws(RuntimeException::class)
protected abstract suspend fun execute(parameters: P): R
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment