Retofit 을 RX 로 Wrapping 해서 API test 를 실행할 수 있다.
Junit5 Gradle 설정
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.2.0'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.2.0'
Retrofit Gradle 설정
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.10.0'
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.4.0
Test 코드 작성
class GitAPITest {
@DisplayName("git Api")
@Test
fun gitAPI() {
val appInfoService = GitRetrofitClient.retrofit.create(GitApiService::class.java)
val source = appInfoService.getGitInfo()
source.doOnNext {
System.out.println(it)
}.test()
.awaitDone(3, TimeUnit.SECONDS)
.assertValue { it ->
System.out.println(it)
it.id.isNotEmpty()
}
.assertComplete()
}
object GitRetrofitClient {
val retrofit: Retrofit
private val CONNECTION_TIMEOUT = 10
private val READ_TIMEOUT = 30
private val WRITE_TIMEOUT = 30
val baseUrl = "https://api.github.com"
init {
val loggingInterceptor = HttpLoggingInterceptor()
loggingInterceptor.level = if (BuildConfig.DEBUG) HttpLoggingInterceptor.Level.BODY else HttpLoggingInterceptor.Level.NONE
val connectionPool = ConnectionPool()
val okHttpClient = OkHttpClient.Builder()
.connectTimeout(CONNECTION_TIMEOUT.toLong(), TimeUnit.SECONDS)
.readTimeout(READ_TIMEOUT.toLong(), TimeUnit.SECONDS)
.writeTimeout(WRITE_TIMEOUT.toLong(), TimeUnit.SECONDS)
.connectionPool(connectionPool)
.addInterceptor(loggingInterceptor)
.build()
retrofit = Retrofit.Builder()
.addConverterFactory(StringConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create(Gson()))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(okHttpClient)
.baseUrl(baseUrl)
.build()
}
}
interface GitApiService {
@GET("/users/babosamo")
fun getGitInfo(): Observable<GitModel>
}
data class GitModel(val login: String, val id: String)
}