'How to provide test retrofit url with Hilt
In my application I started to use Hilt as DI. So I create a class to provide retrofit in in my repository like this
@InstallIn(ApplicationComponent::class)
object RetrofitModule {
var baseUrl = "https://my.fancy.api"
@Singleton
@Provides
fun providesRetrofitClient(): Retrofit {
return Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.client(providesOkHttpClient())
.build()
}
@Singleton
@Provides
fun providesOkHttpClient(): OkHttpClient {
val okHttpClientBuilder = OkHttpClient.Builder()
val loggingInterceptor = HttpLoggingInterceptor().apply {
level = HttpLoggingInterceptor.Level.BODY
}
okHttpClientBuilder.addInterceptor(loggingInterceptor)
return okHttpClientBuilder.build()
}
@Singleton
@Provides
fun providesJokeGeneratorService(retrofit: Retrofit): FancyApiService {
return retrofit.create(FancyApiService::class.java)
}
My question, how can I change the url to use it in the Mockwebserver with Hilt?
Solution 1:[1]
If you are using different build variants to separate mock from real, you can create two classes with exact name in both mock and real package and extent RetrofitModule from that class. Then put differences such as baseUrl and etc. in those two classes.
class RetrofitModuleConstants {
val baseUrl = "https://my.fancy.api"
}
@InstallIn(ApplicationComponent::class)
object RetrofitModule : RetrofitModuleConstants {
...
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Erfan Gholami |
