如何使用 Hilt 提供测试改造 url

How to provide test retrofit url with Hilt

在我的应用程序中,我开始使用 Hilt 作为 DI。所以我创建了一个 class 来在我的存储库中提供改造,就像这样

@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)
    }

我的问题是,如何更改 url 以在带有 Hilt 的 Mockwebserver 中使用它?

如果您使用不同的构建变体来将模拟与真实分开,您可以创建两个 classes,在模拟和真实包中都具有准确的名称,并且范围 RetrofitModule 来自 class.然后在这两个 class 中放入 baseUrl 等差异。

class RetrofitModuleConstants {

    val baseUrl = "https://my.fancy.api"
}

@InstallIn(ApplicationComponent::class)
object RetrofitModule : RetrofitModuleConstants  {
    ...
}

将模块从 object 更改为 class 并使 baseUrl 变量 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)
    }

然后只需在您的测试源中创建一个新的测试模块:

@Module
@TestInstallIn(
    components = [SingletonComponent::class],
    replaces = [RetrofitModule::class]
)
class TestRetrofitModule : RetrofitModule() {
    override var baseUrl = "https://localhost:8000"
}