Skip to content

Instantly share code, notes, and snippets.

@laithnurie
Last active February 11, 2025 08:49
Show Gist options
  • Save laithnurie/dc8a930aa973a3c25ff51d535190aa42 to your computer and use it in GitHub Desktop.
Save laithnurie/dc8a930aa973a3c25ff51d535190aa42 to your computer and use it in GitHub Desktop.
MockServerRule Test using Ktor
class MockServerRule(
private val appStartUpOverrideMockRequests: List<MockRequest> = emptyList<MockRequest>()
) : TestRule {
private var overrideRequests = mutableMapOf<String, MockRequest>()
override fun apply(
base: Statement,
description: Description
): Statement {
return object : Statement() {
override fun evaluate() {
appStartUpOverrideMockRequests.forEach {
overrideRequests[it.path] = it
}
val server = embeddedServer(CIO, port = 8080) {
intercept(ApplicationCallPipeline.Call) {
overrideRequests[call.request.path()]?.let {
call.respondText(
text = it.response,
status = it.httpStatusCode,
contentType = ContentType.Application.Json
)
finish()
}
}
}.apply {
application.defaultRoutes()
start(wait = false)
}
try {
server.application.monitor.subscribe(ApplicationStarted) {
base.evaluate()
}
} finally {
server.stop(0, 0) // Initiate shutdown
overrideRequests.clear()
}
}
}
}
// mid test override
fun overrideRequest(vararg mockRequests: MockRequest) {
mockRequests.forEach { request ->
overrideRequests[request.path] = request
}
}
fun removeOverrides() {
overrideRequests.clear()
}
}
data class MockRequest(
val path: String,
val response: String,
val httpStatusCode: HttpStatusCode
)
/// usage
@get:Rule(order = 1)
var hiltRule = HiltAndroidRule(this)
@get:Rule(order = 2)
val mockServerRule = MockServerRule()
/**
or pre app start up MockServerRule(listOf(MockRequest(blah blah))
*/
@get:Rule(order = 3)
val composeTestRule = createAndroidComposeRule<MainActivity>()
@Before
fun setUp() {
hiltRule.inject()
}
@Test
fun testSomething() {
// test steps...
// mid test override
mockServerRule.overrideRequest(
MockRequest("/api/error", "{}", HttpStatusCode.BadRequest),
)
// rest of the test
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment