Skip to content

Instantly share code, notes, and snippets.

@pedrovgs
Created December 12, 2019 09:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pedrovgs/498eb310d385e5d40f9419551b4939de to your computer and use it in GitHub Desktop.
Save pedrovgs/498eb310d385e5d40f9419551b4939de to your computer and use it in GitHub Desktop.
Utility class to use mock web server in our tests
import com.google.gson.Gson
import com.google.gson.JsonElement
import com.google.gson.JsonParser
import okhttp3.Headers
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
import okhttp3.mockwebserver.RecordedRequest
import org.apache.commons.io.FileUtils
import org.junit.After
import java.io.File
open class MockWebServerTest {
private val server: MockWebServer = MockWebServer()
val baseUrl = server.url("/").toString()
companion object {
const val GET = "GET"
const val POST = "POST"
const val DELETE = "DELETE"
const val PUT = "PUT"
private const val FILE_ENCODING = "UTF-8"
private const val QUERY_PARAM_DELIMITER = "?"
private val parser = JsonParser()
private val gson = Gson()
}
@After
open fun tearDown() {
server.shutdown()
}
private val lastRequest: RecordedRequest by lazy { server.takeRequest() }
private val body: String by lazy { lastRequest.body.readUtf8() }
private val formParams: Map<String, String> by lazy {
body.split("&").map { field ->
val parts = field.split("=")
parts[0] to parts[1]
}.toMap()
}
val requestMethod: String
get() = lastRequest.method
val requestPath: String
get() {
val path = lastRequest.path.replace("//", "/")
return if (path.contains(QUERY_PARAM_DELIMITER)) {
path.substring(0, path.indexOf(QUERY_PARAM_DELIMITER))
} else {
path
}
}
val requestHeaders: Headers
get() = lastRequest.headers
val requestBody: JsonElement
get() = parser.parse(lastRequest.body.readUtf8())
val requestUrlSegments: List<String>
get() = lastRequest.requestUrl.pathSegments()
fun requestFormParam(value: String): String {
return formParams[value]!!
}
fun requestQueryParam(value: String): String {
return lastRequest.requestUrl.queryParameter(value)!!
}
fun enqueueApiResponse(statusCode: Int = 200, body: Any? = null) {
val response = MockResponse()
response.setResponseCode(statusCode)
if (body != null) {
val jsonBody = gson.toJson(body)
response.setBody(jsonBody)
}
server.enqueue(response)
}
fun enqueueBadRequestResponse() {
enqueueApiResponse(400)
}
fun enqueueUnauthorizedResponse() {
enqueueApiResponse(401)
}
fun enqueueForbiddenResponse() {
enqueueApiResponse(403)
}
fun enqueueServerErrorResponse() {
enqueueApiResponse(500)
}
fun enqueueNotFoundResponse() {
enqueueApiResponse(404)
}
fun jsonFromFile(path: String): JsonElement =
parser.parse(getContentFromFile(path))
private fun getContentFromFile(path: String? = null): String {
if (path == null) {
return ""
}
val file = File(javaClass.getResource(path)!!.file)
val lines = FileUtils.readLines(file, FILE_ENCODING)
val stringBuilder = StringBuilder()
for (line in lines) {
stringBuilder.append(line)
}
return stringBuilder.toString()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment