Hi, is there anybody who are using ktor for REST A...
# test
m
Hi, is there anybody who are using ktor for REST API and has experience in writing IT tests with mocks? Lets assume that I use a kind of service class in my routing. I need to mock that service and test concrete routing / endpoint
j
Extract the things you want to test in an interface and implements it with a Fake for the tests:
Copy code
class TwilioService(...) : SendSms {
   override fun send(message: String) = ...
}
interface SendSms {
   fun send(message: String)
}
data class FakeSendSms(val messages: List<String>) : SendSms {
   override fun send(message: String) = messages += message
}
m
Ok @jmfayard. How you inject fake implementation?
j
Dependency injection by passing an argument to the constructor. Or use Koin! https://insert-koin.io/docs/2.0/getting-started/ktor/
m
I'm trying to use koin DI but I have no idea how create post request to my ktor route:
Copy code
@KtorExperimentalAPI
fun Application.main() {

    install(Koin) {
        modules(appModule)
    }

    routing {
      val service: MyService by inject()
    
      post("/") {
        ...
      }
    }
}

val appModule = module {
    single { MyService() }
}
and my test:
Copy code
class UserConfirmationTest : KoinTest {
    
    val service : MyService by inject()
    
    @test
    fun `sample test`() {
        startKoin { 
            modules(appModule)
        }
        
        declareMock<MyService> { 
            given(this.save()).willReturn()
        }

        // HOW TO CREATE POST REQUEST!
    }
}