Skip to content

Instantly share code, notes, and snippets.

@wada811
Created November 6, 2018 13:47
Show Gist options
  • Save wada811/ec779259fd6efb430ca213782a2d4a94 to your computer and use it in GitHub Desktop.
Save wada811/ec779259fd6efb430ca213782a2d4a94 to your computer and use it in GitHub Desktop.
import RxTest.Result.Error4XX
import RxTest.Result.Error5XX
import RxTest.Result.Success
import io.reactivex.Single
import io.reactivex.observers.TestObserver
import org.junit.Test
class RxTest {
enum class Result {
Success,
Error4XX,
Error5XX
}
class Error4XXException : RuntimeException("4XX error")
class Error5XXException : RuntimeException("5XX error")
private fun test(results: List<Result>): TestObserver<Boolean> {
var retryCount = 0
return Single.create<Boolean> { emitter ->
System.out.println("results[retryCount]: ${results[retryCount]}")
when (results[retryCount]) {
Success -> emitter.onSuccess(true)
Error4XX -> emitter.onError(Error4XXException())
Error5XX -> emitter.onError(Error5XXException())
}
}.retry { count, throwable ->
retryCount = count
System.out.println("retryCount: $retryCount")
when (throwable) {
is Error4XXException -> {
return@retry false // 4XX error はそのまま終了
}
is Error5XXException -> {
if (count <= 3) {
// Thread.sleep(1000)
return@retry true // 5XX error は3回までリトライ
} else {
return@retry false // 3回リトライしても 5XX error ならそのまま終了
}
}
else -> return@retry false
}
}.test()
}
@Test
fun test_Success() {
val results = listOf(Success)
val observer = test(results)
observer.assertValue(true)
observer.assertNoErrors()
}
@Test
fun test_Error4XX() {
val results = listOf(Error4XX)
val observer = test(results)
observer.assertError { throwable ->
System.out.println("throwable: ${throwable.message}")
throwable is Error4XXException
}
}
@Test
fun test_Error5XX_Success() {
val results = listOf(Error5XX, Success)
val observer = test(results)
observer.assertValue(true)
observer.assertNoErrors()
}
@Test
fun test_Error5XX_Error5XX_Success() {
val results = listOf(Error5XX, Error5XX, Success)
val observer = test(results)
observer.assertValue(true)
observer.assertNoErrors()
}
@Test
fun test_Error5XX_Error5XX_Error5XX_Success() {
val results = listOf(Error5XX, Error5XX, Error5XX, Success)
val observer = test(results)
observer.assertValue(true)
observer.assertNoErrors()
}
@Test
fun test_Error5XX_Error5XX_Error5XX_Error5XX() {
val results = listOf(Error5XX, Error5XX, Error5XX, Error5XX)
val observer = test(results)
observer.assertError { throwable ->
System.out.println("throwable: ${throwable.message}")
throwable is Error5XXException
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment