https://kotlinlang.org logo
Channels
100daysofcode
100daysofkotlin
100daysofkotlin-2021
advent-of-code
aem
ai
alexa
algeria
algolialibraries
amsterdam
android
android-architecture
android-databinding
android-studio
androidgithubprojects
androidthings
androidx
androidx-xprocessing
anime
anko
announcements
apollo-kotlin
appintro
arabic
argentina
arkenv
arksemdevteam
armenia
arrow
arrow-contributors
arrow-meta
ass
atlanta
atm17
atrium
austin
australia
austria
awesome-kotlin
ballast
bangladesh
barcelona
bayarea
bazel
beepiz-libraries
belgium
benchmarks
berlin
big-data
books
boston
brazil
brikk
budapest
build
build-tools
bulgaria
bydgoszcz
cambodia
canada
carrat
carrat-dev
carrat-feed
chicago
chile
china
chucker
cincinnati-user-group
cli
clikt
cloudfoundry
cn
cobalt
code-coverage
codeforces
codemash-precompiler
codereview
codingame
codingconventions
coimbatore
collaborations
colombia
colorado
communities
competitive-programming
competitivecoding
compiler
compose
compose-android
compose-desktop
compose-hiring
compose-ios
compose-mp
compose-ui-showcase
compose-wear
compose-web
confetti
connect-audit-events
corda
cork
coroutines
couchbase
coursera
croatia
cryptography
cscenter-course-2016
cucumber-bdd
cyprus
czech
dagger
data2viz
databinding
datascience
dckotlin
debugging
decompose
decouple
denmark
deprecated
detekt
detekt-hint
dev-core
dfw
docs-revamped
dokka
domain-driven-design
doodle
dsl
dublin
dutch
eap
eclipse
ecuador
edinburgh
education
effective-kotlin
effectivekotlin
emacs
embedded-kotlin
estatik
event21-community-content
events
exposed
failgood
fb-internal-demo
feed
firebase
flow
fluid-libraries
forkhandles
forum
fosdem
fp-in-kotlin
framework-elide
freenode
french
fritz2
fuchsia
functional
funktionale
gamedev
ge-kotlin
general-advice
georgia
geospatial
german-lang
getting-started
github-workflows-kt
glance
godot-kotlin
google-io
gradle
graphic
graphkool
graphql
graphql-kotlin
graviton-browser
greece
grpc
gsoc
gui
hackathons
hacktoberfest
hamburg
hamkrest
helios
helsinki
hexagon
hibernate
hikari-cp
hire-me
hiring
hiring-french
hongkong
hoplite
http4k
hungary
hyderabad
image-processing
india
indonesia
inkremental
intellij
intellij-plugins
intellij-tricks
internships
introduce-yourself
io
ios
iran
israel
istanbulcoders
italian
jackson-kotlin
jadx
japanese
jasync-sql
java-to-kotlin-refactoring
javadevelopers
javafx
javalin
javascript
jdbi
jhipster-kotlin
jobsworldwide
jpa
jshdq
juul-libraries
jvm-ir-backend-feedback
jxadapter
k2-early-adopters
kaal
kafka
kakao
kalasim
kapt
karachi
karg
karlsruhe
kash_shell
kaskade
kbuild
kdbc
kgen-doc-tools
kgraphql
kinta
klaxon
klock
kloudformation
kmdc
kmm-español
kmongo
knbt
knote
koalaql
koans
kobalt
kobweb
kodein
kodex
kohesive
koin
koin-dev
komapper
kondor-json
kong
kontent
kontributors
korau
korean
korge
korim
korio
korlibs
korte
kotest
kotest-contributors
kotless
kotlick
kotlin-asia
kotlin-beam
kotlin-by-example
kotlin-csv
kotlin-data-storage
kotlin-foundation
kotlin-fuel
kotlin-in-action
kotlin-inject
kotlin-latam
kotlin-logging
kotlin-multiplatform-contest
kotlin-mumbai
kotlin-native
kotlin-pakistan
kotlin-plugin
kotlin-pune
kotlin-roadmap
kotlin-samples
kotlin-sap
kotlin-serbia
kotlin-spark
kotlin-szeged
kotlin-website
kotlinacademy
kotlinbot
kotlinconf
kotlindl
kotlinforbeginners
kotlingforbeginners
kotlinlondon
kotlinmad
kotlinprogrammers
kotlinsu
kotlintest
kotlintest-devs
kotlintlv
kotlinultimatechallenge
kotlinx-datetime
kotlinx-files
kotlinx-html
kotrix
kotson
kovenant
kprompt
kraph
krawler
kroto-plus
ksp
ktcc
ktfmt
ktlint
ktor
ktp
kubed
kug-leads
kug-torino
kvision
kweb
lambdaworld_cadiz
lanark
language-evolution
language-proposals
latvia
leakcanary
leedskotlinusergroup
lets-have-fun
libgdx
libkgd
library-development
lincheck
linkeddata
lithuania
london
losangeles
lottie
love
lychee
macedonia
machinelearningbawas
madrid
malaysia
mathematics
meetkotlin
memes
meta
metro-detroit
mexico
miami
micronaut
minnesota
minutest
mirror
mockk
moko
moldova
monsterpuzzle
montreal
moonbean
morocco
motionlayout
mpapt
mu
multiplatform
mumbai
munich
mvikotlin
mvrx
myndocs-oauth2-server
naming
navigation-architecture-component
nepal
new-mexico
new-zealand
newname
nigeria
nodejs
norway
npm-publish
nyc
oceania
ohio-kotlin-users
oldenburg
oolong
opensource
orbit-mvi
osgi
otpisani
package-search
pakistan
panamá
pattern-matching
pbandk
pdx
peru
philippines
phoenix
pinoy
pocketgitclient
polish
popkorn
portugal
practical-functional-programming
proguard
prozis-android-backup
pyhsikal
python
python-contributors
quasar
random
re
react
reaktive
realm
realworldkotlin
reductor
reduks
redux
redux-kotlin
refactoring-to-kotlin
reflect
refreshversions
reports
result
rethink
revolver
rhein-main
rocksdb
romania
room
rpi-pico
rsocket
russian
russian_feed
russian-kotlinasfirst
rx
rxjava
san-diego
science
scotland
scrcast
scrimage
script
scripting
seattle
serialization
server
sg-user-group
singapore
skia-wasm-interop-temp
skrape-it
slovak
snake
sofl-user-group
southafrica
spacemacs
spain
spanish
speaking
spek
spin
splitties
spotify-mobius
spring
spring-security
squarelibraries
stackoverflow
stacks
stayhungrystayfoolish
stdlib
stlouis
strife-discord-lib
strikt
students
stuttgart
sudan
swagger-gradle-codegen
swarm
sweden
swing
swiss-user-group
switzerland
talking-kotlin
tallinn
tampa
teamcity
tegal
tempe
tensorflow
terminal
test
testing
testtestest
texas
tgbotapi
thailand
tornadofx
touchlab-tools
training
tricity-kotlin-user-group
trójmiasto
truth
tunisia
turkey
turkiye
twitter-feed
uae
udacityindia
uk
ukrainian
uniflow
unkonf
uruguay
utah
uuid
vancouver
vankotlin
vertx
videos
vienna
vietnam
vim
vkug
vuejs
web-mpp
webassembly
webrtc
wimix_sentry
wwdc
zircon
Powered by
Title
v

Viktor Orlyk

05/10/2023, 7:59 AM
HI, I want to implement test where I can actually confirm user. My process is user signups he receives an email with link(which includes token) from sendgrid(HtmlEmail from commons.mail) then client make a post request to other my api to confirm. So request to /api/signup will result in request sent to sendgrid. I want to intercept that request in my tests get the body from it and do not send real request to Sendgrid. But send another request with my token to my endpoint. How I can achieve that?
a

Aleksei Tirman [JB]

05/10/2023, 9:05 AM
Can you fake the dependency that sends a request to Sendgrid in a test?
v

Viktor Orlyk

05/10/2023, 9:08 AM
thank you for fast answer, I am not sure how to do that if I have next code in test. Dependency which is making request to sendgrid is
import org.apache.commons.mail.HtmlEmail
// this thing will make request to sendgrid internally
    <http://client.post|client.post>("/api/v1/auth/signup") {
        headers.remove("Authorization")
        contentType(ContentType.Application.Json)
        setBody(body)
    }

    <http://client.post|client.post>("/api/v1/auth/confirm-email") {
        headers.remove("Authorization")
        contentType(ContentType.Application.Json)
        setBody(ConfirmEmailDTO("this should be retrived from call which is made inside of service"))
    }
b

BryanT

05/10/2023, 9:35 AM
I need to write a similar test case but haven't started writing it yet. Based on my limited understanding I was going to try using the MockEngine for my client, if that is applicable to your use case. https://github.com/ktorio/ktor-documentation/blob/main/codeSnippets/snippets/client-testing-mock/src/test/kotlin/ApplicationTest.kt
a

Aleksei Tirman [JB]

05/10/2023, 9:40 AM
@Viktor Orlyk can you explain what behavior you need to test?
v

Viktor Orlyk

05/10/2023, 10:12 AM
@BryanT yes I was thinking about MockEngine, but haven’t found how to use it to actually do that. @Aleksei Tirman [JB] I want to write end to end test which will go through full sign up proccess: 1. sign up(post to my server) 2. email with token( done in server) 3. confirmation request (post to my server) I was thinking about wiremock, but haven’t found how to extract the request from it and reuse data from it. My other thoughts are next code.
class AuthSpec : FreeSpec({
  val ds = createDataSourceTest()
  "check login functionality" - {
    "login confirmed user" - {
      val signupData = SignupDTO("<mailto:giloja3553@andorem.com|giloja3553@andorem.com>", "<mailto:Giloja3553@andorem.com|Giloja3553@andorem.com>")
      testApplication {
        val client  = createApplicationAndGetClient(ds)
        <http://client.post|client.post>("/api/v1/auth/signup") {
          headers.remove("Authorization")
          contentType(ContentType.Application.Json)
          setBody(body)
        }
// somehow  I need to intercept previout request to sendgrid and retrieve token and use it in request below
        <http://client.post|client.post>("/api/v1/auth/confirm-email") {
          headers.remove("Authorization")
          contentType(ContentType.Application.Json)
          setBody(ConfirmEmailDTO("hello"))
        }
        val loginResponse = <http://client.post|client.post>("/api/v1/auth/login"){
          headers.remove("Authorization")
          contentType(ContentType.Application.Json)
          setBody(LoginDTO(signupData.email, signupData.password))
        }
        val body = loginResponse.body<LoginResponseDTO>()
        body.access.shouldNotBeNull()
        body.refresh.shouldNotBeNull()
      }
    }
  }
})
my initial thought was to create a mock client but it fails for some reason
val mockEngine = MockEngine { call ->
        when (call.url.toString()) {
            "<https://api.sendgrid.com/v3/mail/send>" -> {
                println(call.body)
                respond(content = "Ok", status = HttpStatusCode.OK)
            }
            else -> {
                error("Unhandled ${call.url}")
            }
        }
    }
    val mockClient = HttpClient(mockEngine){
        install(ContentNegotiation){
            json()
        }
    }
<http://mockClient.post|mockClient.post>("/api/v1/auth/signup").....
but it fails with next error
Unhandled <http://localhost/api/v1/auth/signup>
java.lang.IllegalStateException: Unhandled <http://localhost/api/v1/auth/signup>
	at com.coinypal.features.auth.AuthSpec$1$1$1$1$mockEngine$1.invokeSuspend(AuthSpec.kt:29)
	at com.coinypal.features.auth.AuthSpec$1$1$1$1$mockEngine$1.invoke(AuthSpec.kt)
	at com.coinypal.features.auth.AuthSpec$1$1$1$1$mockEngine$1.invoke(AuthSpec.kt)
	at io.ktor.client.engine.mock.MockEngine.execute(MockEngine.kt:71)
	at io.ktor.client.engine.HttpClientEngine$executeWithinCallContext$2.invokeSuspend(HttpClientEngine.kt:99)
	at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
	at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
	at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:570)
	at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:750)
	at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:677)
	at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:664)
if I use this mockClient instead of client which was created and returned in the first code block
fun ApplicationTestBuilder.createApplicationAndGetClient(ds:DataSource): HttpClient {
  application{
    DbFactory.init(ds)

    configureExceptions()
    configureDependencyInjection()
    configureMustache()
    configureCors()
    configureSerialization()
    configureAuthentication()
    configureRouting()
  }

  return createClient {
    install(ContentNegotiation){
      json()
    }
  }
}
a

Aleksei Tirman [JB]

05/11/2023, 2:48 PM
You can pass a fake version of the service, that sends requests to SendGrid, inside the
application
block of
testApplication
by manually calling the module function.
v

Viktor Orlyk

05/11/2023, 3:26 PM
@Aleksei Tirman [JB] so there is no way to intercept that request currently? because I did that as a simple function which is just called, not module which is injected via some di. Or maybe i don’t understand how i can replace that function which is nested somewhere in the service layer with something new. Anyway thank you for answers!
I moved quite far with my solution but probably I am missing something important in MockEngine work, for some reason it does not sotp in debugger in inside of MockEngine
"login confirmed user" - {
      val signupData = SignupDTO("<mailto:giloja3553@andorem.com|giloja3553@andorem.com>", "<mailto:Giloja3553@andorem.com|Giloja3553@andorem.com>")
      testApplication {
        var token: String = "this should be changed"
        val mockClient = createClient {
          engine {
            MockEngine { call ->
              when (call.url.toString()) {
                "<https://api.sendgrid.com/v3/mail/send>" -> {
                  println("hello ${call.body}")
                  token = call.body.toString() // here I will find the token
                  respond(content = "Ok", status = HttpStatusCode.OK)
                }
                else -> {
                  error("Unhandled ${call.url}")
                }
              }
            }
          }
          install(ContentNegotiation){
            json()
          }

        }
        val client  = createApplicationAndGetClient(ds)
        <http://mockClient.post|mockClient.post>("/api/v1/auth/signup") {
          headers.remove("Authorization")
          contentType(ContentType.Application.Json)
          setBody(body)
        }

        <http://client.post|client.post>("/api/v1/auth/confirm-email") {
          headers.remove("Authorization")
          contentType(ContentType.Application.Json)
          setBody(ConfirmEmailDTO(token))
        }
        val loginResponse = <http://client.post|client.post>("/api/v1/auth/login"){
          headers.remove("Authorization")
          contentType(ContentType.Application.Json)
          setBody(LoginDTO(signupData.email, signupData.password))
        }
        val body = loginResponse.body<LoginResponseDTO>()
        body.access.shouldNotBeNull()
        body.refresh.shouldNotBeNull()
      }
    }
a

Aleksei Tirman [JB]

05/15/2023, 7:28 AM
That’s because you create an instance of the
MockEngine
inside the
engine
’s block but don’t assign it. You can’t change the engine of the client inside the
testApplication
.