10
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

RetrofitのAPIレスポンスをモッキング

Posted at

コードのテストをしたり、APIがまだ未実装だったりで、モックが欲しかったのでそのメモ。

導入

Retrofit Mockを使う。

def retrofit_version = '2.7.0'
implementation "com.squareup.retrofit2:retrofit:$retrofit_version"
implementation "com.squareup.retrofit2:retrofit-mock:$retrofit_version"

実装

サービスインタフェースを実装したモックを作成し、そこに返したいデータを書く。

Service.kt
interface Service {

    @GET("api/v1/auth")
    fun getAuth(@Query("id") id: String): Single<Auth>

    @GET("api/v1/payment")
    fun getPayment(@Query("token") token: String): Single<List<Payment>>
}
MockService.kt
class MockService(private val delegate: BehaviorDelegate<Service>) : Service {

    override fun getAuth(id: String): Single<Auth> {
        val auth = Auth("xxx")
        return delegate.returningResponse(auth).getAuth(id)
    }

    override fun getPayment(token: String): Single<List<Payment>> {
        val payment = Payment(1000)
        return delegate.returningResponse(listOf(payment)).getPayment(token)
    }
}

あとはAPI生成時にモックを返すようにすればOK。

Api.kt
class Api {

    companion object {

        fun create(): Service {
            val retrofit = Retrofit.Builder()
                .baseUrl("https://mock.com/")
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(MoshiConverterFactory.create())
                .build()

            val behavior = NetworkBehavior.create()

            val mockRetrofit = MockRetrofit.Builder(retrofit)
                .networkBehavior(behavior)
                .build()

            val delegate = mockRetrofit.create(Service::class.java)

            return MockService(delegate)
        }
    }
}

補足

モック生成時にデフォルト値が設定されている項目があるので、随時変更すること。

val behavior = NetworkBehavior.create()
behavior.setDelay(100, TimeUnit.MILLISECONDS)
behavior.setVariancePercent(0)
behavior.setFailurePercent(0)
behavior.setErrorPercent(0)
項目 内容 デフォルト値
Delay 発生する遅延 2000ms
VariancePercent 発生する遅延の割合 ±40%
FailurePercent 発生する失敗の割合 3%
ErrorPercent 発生するエラーの割合 0%

作ったやつ

demo-retro-mock

10
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?