Reputation: 5732
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?
Upvotes: 1
Views: 1133
Reputation: 14399
Change your module from object
to class
and make the baseUrl
variable open
:
@InstallIn(SingletonComponent::class)
open class RetrofitModule {
open 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)
}
Then simply create a new test module inside your test source:
@Module
@TestInstallIn(
components = [SingletonComponent::class],
replaces = [RetrofitModule::class]
)
class TestRetrofitModule : RetrofitModule() {
override var baseUrl = "https://localhost:8000"
}
Upvotes: 1
Reputation: 21
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 {
...
}
Upvotes: 0