app: port tests to Ktor

Signed-off-by: Harsh Shandilya <me@msfjarvis.dev>
This commit is contained in:
Harsh Shandilya 2020-11-08 17:04:23 +05:30
parent d01a7e18a2
commit abe6c4c2b8
No known key found for this signature in database
GPG key ID: 366D7BBAD1031E80
5 changed files with 93 additions and 0 deletions

View file

@ -99,6 +99,7 @@ dependencies {
implementation(Dependencies.ThirdParty.customtabs)
implementation(Dependencies.ThirdParty.Roomigrant.runtime)
testImplementation(Dependencies.Testing.junit)
testImplementation(Dependencies.Kotlin.Ktor.clientTest)
androidTestImplementation(Dependencies.Testing.daggerHilt)
androidTestImplementation(Dependencies.Testing.uiTest)
}

View file

@ -0,0 +1,78 @@
package dev.msfjarvis.lobsters.data.api
import dev.msfjarvis.lobsters.util.TestUtils
import io.ktor.client.HttpClient
import io.ktor.client.engine.mock.MockEngine
import io.ktor.client.engine.mock.respond
import io.ktor.client.features.json.JsonFeature
import io.ktor.client.features.json.serializer.KotlinxSerializer
import io.ktor.http.fullPath
import io.ktor.http.headersOf
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import kotlinx.coroutines.runBlocking
import org.junit.AfterClass
import org.junit.BeforeClass
import org.junit.Test
class KtorLobstersApiTest {
companion object {
@JvmStatic
private lateinit var client: HttpClient
@JvmStatic
private lateinit var apiClient: LobstersApi
@JvmStatic
@BeforeClass
fun setUp() {
client = HttpClient(MockEngine) {
install(JsonFeature) {
serializer = KotlinxSerializer()
}
engine {
addHandler { request ->
when (request.url.fullPath) {
"/hottest.json?page=1" -> {
val responseHeaders = headersOf("Content-Type" to listOf("application/json"))
respond(TestUtils.getJson("hottest.json"), headers = responseHeaders)
}
else -> error("Unhandled ${request.url.fullPath}")
}
}
}
}
apiClient = KtorLobstersApi(client)
}
@JvmStatic
@AfterClass
fun tearDown() {
client.close()
}
}
@Test
fun `api gets correct number of items`() = runBlocking {
val posts = apiClient.getHottestPosts(1)
assertEquals(25, posts.size)
}
@Test
fun `no moderator posts in test data`() = runBlocking {
val posts = apiClient.getHottestPosts(1)
val moderatorPosts = posts.asSequence()
.filter { it.submitterUser.isModerator }
.toSet()
assertTrue(moderatorPosts.isEmpty())
}
@Test
fun `posts with no urls`() = runBlocking {
val posts = apiClient.getHottestPosts(1)
val commentsOnlyPosts = posts.asSequence()
.filter { it.url.isEmpty() }
.toSet()
assertEquals(2, commentsOnlyPosts.size)
}
}

View file

@ -0,0 +1,12 @@
package dev.msfjarvis.lobsters.util
import java.io.File
object TestUtils {
fun getJson(path: String): String {
// Load the JSON response
val uri = javaClass.classLoader.getResource(path)
val file = File(uri.path)
return String(file.readBytes())
}
}

File diff suppressed because one or more lines are too long