Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
1
Help us understand the problem. What is going on with this article?
@toranokopg

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

More than 1 year has passed since last update.

コードのテストをしたり、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

1
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
toranokopg
カレーをよく食べます。

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
1
Help us understand the problem. What is going on with this article?