1

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?

dudi
  • 5,523
  • 4
  • 28
  • 57

2 Answers2

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"
}
Roberto Leinardi
  • 10,641
  • 6
  • 65
  • 69
0

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  {
    ...
}
Erfan Gholami
  • 21
  • 1
  • 8