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
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
c

Colton Idle

04/22/2023, 11:18 PM
I have a set of 10 unit tests. In reality it's just 5 unit tests duplicated because I test with my prod url and my staging url. If I want to de-dupe them, whats the best way to do that in junit4? seems like paramterized tests might be what i want BUT parameterized tests make you define an input and output. i just want to change the inputs. Is there some other feature of junit I'm missing?
c

Chris Lee

04/22/2023, 11:28 PM
Use parameterized tests. There is no such thing as a parameterized test output. The parameters can be used for whatever the test requires.
c

Colton Idle

04/22/2023, 11:36 PM
Alright. I will go for that. FWIW, an example of my current test is
@Test
fun `test prod`() = runBlocking {
        val apolloClient = ApolloClient.Builder()
            .serverUrl("my prod url")
            .build()

        val result =  ..
        assert(result.isSuccess)
}
and
@Test
fun `test staging`() = runBlocking {
        val apolloClient = ApolloClient.Builder()
            .serverUrl("my staging url")
            .build()

        val result =  ..
        assert(result.isSuccess)
}
so I just would like to combine those two into 1
c

Chris Lee

04/22/2023, 11:39 PM
could drop them into a utility method that takes the server url as a paramter.
e

ephemient

04/22/2023, 11:41 PM
it's a bit more awkward in JUnit 4 than it is in JUnit 5, but
@RunWith(Parameterized::class)
class MyTest(val serverUrl: String) {
    @Test
    fun test() = runBlocking {
        val apolloClient = ApolloClient.Builder()
            .serverUrl(serverUrl)
            .build()
    }

    companion object {
        @JvmStatic
        @Parameterized.Parameters(name = "{0}")
        fun data(): Iterable<Array<*>> = listOf(
            arrayOf("my prod url"),
            arrayOf("my staging url"),
        )
    }
}
JUnit 5's
@ParameterizedTest
@ValueSource(strings = ["my prod url", "my staging url"]
fun test(serverUrl: String) {
    // ...
is more concise and more flexible, if you can migrate
c

Colton Idle

04/22/2023, 11:54 PM
oh hell yeah. junit 4's is awkware. while we're here... and it just took me 15 minutes to get dependencies squared away. what the heck is junit vs jupiter. lol
c

Colton Idle

04/23/2023, 12:00 AM
thanks @ephemient
FWIW, I was able to simplify the data() method a bit
@JvmStatic
      @Parameterized.Parameters(name = "{0}")
      fun data(): Iterable<Any> = listOf(
        "my prod url",
        "my staging url",
      )
e

ephemient

04/23/2023, 1:05 AM
you need an array to wrap multiple parameters and I usually pass one specifically for test naming, but if that works then sure
e.g.
class MyTest(ignoredName: String, val serverUrl: String) {
    companion object {
        @JvmStatic
        @Parameterized.Parameters(name = "{0}")
        fun data(): Iterable<Array<*>> = listOf(
            arrayOf("prod", "my prod url"),
            arrayOf("staging", "my staging url"),
        )
the
{0}
makes it shows up as
[prod]
or
[staging]
in the test report
if the argument you're passing is naturally identifiable by
toString
then it doesn't matter of course, and if you don't mind the default index-based naming, then I guess you don't need to bother either
c

Colton Idle

04/23/2023, 1:09 AM
oh. cool. i didn't notice that difference. i'll use that instead. cheers
e

eygraber

04/23/2023, 1:41 AM
Just as an aside, are you actually making requests to your server? If so, these are probably closer to integration tests, and not unit tests.
e

ephemient

04/23/2023, 1:42 AM
yeah good point, if that's the case I'd create separate test configurations for different environments instead
c

Colton Idle

04/24/2023, 4:13 AM
Yeah, they are not unit tests, but we would like to test e2e request being made + deserialization. "seaprate test configuration" hm. any docs you can point to for that? noob here that doesn't know what that means
k

kqr

04/24/2023, 6:35 AM
this looks like environment specific thing, that should be "injected" to your app as regular external config
e

ephemient

04/24/2023, 10:21 PM
you can split it out from your unit tests and inject it into the test environment, e.g.
plugins {
    `jvm-test-suite`
}
testing {
    suites {
        val integrationTest by registering(JvmTestSuite::class) {
            useJUnit()
            targets.all {
                testTask.configure {
                    systemProperty("serverUrl", project.property("serverUrl"))
                }
            }
        }
    }
}
with a
val serverUrl: String = System.getProperty("serverUrl")
lookup in
src/integrationTest/kotlin/*
and running with
./gradlew integrationTest -PserverUrl='my staging url'
or
-PserverUrl='my prod url'
, etc.
you could even hack together
val integrationTest by sourceSets.creating
dependencies {
    integrationTest.implementationConfigurationName(kotlin("test-junit"))
}
testing {
    suites {
        val stagingIntegrationTest by registering(JvmTestSuite::class) {
            dependencies {
                implementation(files(integrationTest.runtimeClasspath))
            }
            useJUnit()
            targets.all {
                testTask.configure {
                    systemProperty("serverUrl", "my staging url")
                    testClassesDirs = files(testClassesDirs, integrationTest.output.classesDirs)
                }
            }
        }
        val prodIntegrationTest by registering(JvmTestSuite::class) {
            dependencies {
                implementation(files(integrationTest.runtimeClasspath))
            }
            useJUnit()
            targets.all {
                testTask.configure {
                    systemProperty("serverUrl", "my prod url")
                    testClassesDirs = files(testClassesDirs, integrationTest.output.classesDirs)
                }
            }
        }
    }
}
if you would rather have separate tests executions for different pre-defined environment using the same test classes
c

Colton Idle

04/25/2023, 12:47 PM
Thanks. is it silly to say that I want my test to just always test all of my 3 environments? i also setup a system property so that you can invoke this from command line, and give it a new url if you want. I will have to try to see the benefit of implementing the above vs my current route.
thanks though everyone. ive learned a ton. ❤️
d

dewildte

04/26/2023, 8:23 PM
E2E in a JUnit4/5 test is like a 🐇 🕳️ 🛣️ to:headstone:. E2E in any kind of non manual test to me smells like red flags.
e

eygraber

04/26/2023, 8:47 PM
I don't know about it being to be manual, but JUnit is called J*Unit* for a reason
c

Chris Lee

04/26/2023, 8:49 PM
if done properly - perhaps in a separate module, or separate application - JUnit makes a nice framework, along with something like RestAssured, to drive E2E tests. Just don’t try and shoehorn them in alongside unit tests.
e

ephemient

04/26/2023, 9:06 PM
separate test suite within the same module is fine too, as Gradle's
jvm-test-suite
makes easy
c

Colton Idle

04/27/2023, 12:08 AM
Yeah. I know that its sorta e2e (its not really like UI e2e test, but testing that a network call works and is deserialized properly catches like 90% of our bugs). so i dont really have any other thoughts on how to structure this. open to ideas.
e

ephemient

04/27/2023, 7:53 AM
sounds more like you need a way to share a JSON schema between projects; testing serialization/deserialization on live services is just a workaround
c

Colton Idle

04/27/2023, 12:21 PM
I guess, but it's moreso that the backend just gets into a completed effed up state and sends us back gibberish sometimes. so the schema hasn't changed, its just the backend being a pain.
i complain to backend devs and they're like "i see that that endpoint 200s. must be a client code issue"
but in reality its some deeply nested thing thats broken and breaks deserialization
e

eygraber

04/27/2023, 1:56 PM
Sounds like you might need unit tests on the backend 😅
d

dewildte

04/27/2023, 7:24 PM
Yeah. I know that its sorta e2e (its not really like UI e2e test, but testing that a network call works and is deserialized properly catches like 90% of our bugs). so i dont really have any other thoughts on how to structure this. open to ideas.
Would a more simple test that proves you can deserialize the expected JSON suffice? You could store the JSON (and variants of it even) in a file and then run it against the test. If it is just deserialization that is needed then you do not need to connect to the real server for that. A simple test like this could be used to prove you can handle proposed responses from an endpoint before the endpoint is even deployed and operational.
e

ephemient

04/27/2023, 10:08 PM
it's a sporadic backend problem, and you're expecting frontend tests to catch it? IMO that really should be the responsibility of the backend to validate its own output
d

dewildte

04/27/2023, 10:39 PM
I implying that the client should know if they can or can not handle valid and invalid JSON responses.
c

Chris Lee

04/27/2023, 10:39 PM
yea, but you can validate that internally w/o having a flaky server to talk to
d

dewildte

04/27/2023, 10:43 PM
I have found this article to be very useful over the years: https://learn.microsoft.com/en-us/azure/architecture/patterns/anti-corruption-layer
I acknowledge this is talking about server development but the principals/pattern itself is platform agnostic.
User this pattern when:
• Two or more subsystems have different semantics, but still need to communicate.
e

eygraber

04/27/2023, 10:46 PM
Looking forward to reading that, since we practice defensive programming to defend ourselves from our backend team's style which is adversarial programming 😅
c

Chris Lee

04/27/2023, 10:47 PM
Give offensive programming a try ;)
d

dewildte

04/27/2023, 10:48 PM
At first glance I looked at that and thought it was going to suggest to add cuss words to logs and do other nefarious things.
c

Chris Lee

04/27/2023, 10:49 PM
well, you can always still do that :blob-sweat-smile:
d

dewildte

04/27/2023, 10:49 PM
I will abstain lol
e

ephemient

04/27/2023, 10:49 PM
"the best defense is a good offense"
e

eygraber

04/27/2023, 10:54 PM
I would've thought it means that if the backend sends back invalid data, we should catch that, and in response send them a bunch of invalid requests.
Maybe that's Mutually Assured Destruction programming
c

Chris Lee

04/27/2023, 10:55 PM
seems like we’ve lowered ourselves to internal denial-of-service. MAD indeed!
c

Colton Idle

04/28/2023, 6:23 AM
I 100% agree that backend tests should catch this etc. But they dont. and they dont write proper tests. ive brought it up with my manager etc. and it drives me crazy to get bug reports constantly opened for the android app. So by writing tests in the android codebase that I can execute... it basically allows me to do a full health check of the app without having to run the app and explore every leaf/screen of the app to find out that something stupid is broken again. I initially was trying to write critical path E2E UI tests to test this, but just checking the network layer specifically has had great results. i literally just run this every 15 minutes and ping myself on slack, which i then yell at the backend team that thier servicec messed up again.
i hate it
but it pays the bills.
e

eygraber

04/28/2023, 2:53 PM
Sounds like there are bigger issues that tests can't fix 😬
c

Colton Idle

04/28/2023, 3:09 PM
but tests can catch them though. and thats all i need. 😄