以下の文言は、AI (ChatGPT4) による出力結果です。そのため内容が一部不正確である可能性があります。
開発中にサーバーサイドの実装がまだ完了していない場合、フロントエンドの開発をスムーズに進めるためには、モックレスポンスを返す方法が役立ちます。今回は、サンプルアプリ zero-2023-android を元に、Retrofit2 を使って MockInterceptor を利用し、モックレスポンスを返す方法を解説します。
1. MockInterceptorの実装
まずはじめに、MockInterceptor クラスを実装します。これにより、アプリがサーバーにリクエストを送る代わりに、内部で定義したモックレスポンスを返すことができます。リポジトリ内の MockInterceptor.kt に実装があります。
2. RetrofitにMockInterceptorを追加
次に、Retrofit のインスタンスを作成する際に、MockInterceptor を追加します。リポジトリ内の ApiModule.kt に実装があります。
@Module
@InstallIn(SingletonComponent::class)
object ApiModule {
@Provides
@Singleton
fun provideMockInterceptor(@ApplicationContext context: Context): MockInterceptor {
return MockInterceptor(context)
}
@Provides
@Singleton
fun provideOkHttpClient(mockInterceptor: MockInterceptor): OkHttpClient {
return OkHttpClient.Builder()
.addInterceptor(mockInterceptor)
.build()
}
@Provides
@Singleton
fun provideRetrofit(okHttpClient: OkHttpClient): Retrofit {
return Retrofit.Builder()
.baseUrl("https://api.example.com")
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.build()
}
}
このコードでは、provideMockInterceptor で MockInterceptor を生成し、provideOkHttpClient で生成された OkHttpClient に追加しています。最後に、provideRetrofit で、設定した OkHttpClient を使用して Retrofit のインスタンスを作成しています。
3. JSONリソースの準備
モックレスポンスとして返す JSON をアプリのリソースに配置します。リポジトリ内にある mock ディレクトリに、モック用の JSON ファイルが格納されています。例として、以下のような JSON ファイルが用意されています。
mock/api1.json
{
"key1": "value1",
"key2": "value2"
}
mock/api2.json
{
"key1": "value3",
"key2": "value4"
}
MockInterceptor では、
context.assets.open(mockResponseFile).bufferedReader().use { it.readText() }
により、リソースに格納された JSON ファイルを読み込み、モックレスポンスとして返しています。
これにより、サーバーサイドの実装が未完成であっても、アプリの開発をスムーズに進めることができます。サーバーとの接続が不要な状況でも、モックレスポンスを利用して UI やロジックの開発を行うことが可能です。