0

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

@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 中使用它?

4

2 回答 2

1

将您的模块从更改objectclass并制作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"
}
于 2022-01-24T11:42:59.340 回答
0

如果您使用不同的构建变体将模拟与真实分开,您可以在模拟和真实包中创建两个具有确切名称的类,以及RetrofitModule该类的范围。然后在这两个类中放置诸如baseUrl等之类的差异。

class RetrofitModuleConstants {

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

@InstallIn(ApplicationComponent::class)
object RetrofitModule : RetrofitModuleConstants  {
    ...
}
于 2020-07-20T13:23:15.967 回答