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:

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"
}