https://kotlinlang.org logo
Join the conversationJoin Slack
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
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
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
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 Linen
test
  • k

    kevin.cianfarini

    11/28/2018, 7:11 PM
    using mocking, how would I mock the return of
    this.walk()
    ?
    o
    • 2
    • 2
  • u

    ursus

    11/30/2018, 2:22 PM
    When one should use interfaces over mocking framework?
    m
    f
    c
    • 4
    • 10
  • v

    vkholyavin

    12/11/2018, 9:23 AM
    Hello! How mock functional argument?
    val myFunction = mock<(String) -> Unit>()
    // actions
    verify(myFunction).invoke(captor.capture())
    throws: java.lang.IllegalStateException: captor.capture() must not be null
    n
    • 2
    • 2
  • c

    cesards

    12/12/2018, 8:52 PM
    Problem solved. We are using
    kluent
    and
    mockito kotlin
    and apparently mockito kotlin buid hasn’t been updated for a while so it was exposing apis that shouldn’t be exposed: https://github.com/nhaarman/mockito-kotlin/blob/2.x/mockito-kotlin/build.gradle#L35
    n
    • 2
    • 3
  • d

    Dhanapal

    01/02/2019, 7:10 AM
    Hi everyone, Is there any way to modify value of
    val
    in test case other than reflection. I don't want this variable gets modified in main package. Appreciate you help.
    o
    t
    • 3
    • 9
  • s

    Smorg

    01/04/2019, 7:25 AM
    Hi guys, I am currently using
    mockito-kotlin
    in my project, and I saw from the docs that I can assign a property to a mock without actually having to use stubs. But this does not seem to be working in my code.
    @Test
    fun testCase() {
        val entity = mock<Entity>()
        entity.property = Property()
        assert(entity.property != null) // fails
    }
    Or does it only work with primitive types or interfaces?
    d
    • 2
    • 2
  • m

    matt tighe

    01/10/2019, 1:00 AM
    i’m having trouble with verification of suspending functions with mockito failing randomly. the tests most often pass, but will occasionally fail and i’m not sure why. for example:
    @Test
        fun `Submits app selection if selections can be made`() {
            mainActivityViewModel.submitAppSelection(selectedApp)
    
            runBlocking {
                verify(mockAppsStartupFsm).submitEvent(AppSelected(selectedApp))
            }
        }
    class MainActivityViewModel {
        fun submitAppSelection(app: App) {
            if (!selectionsCanBeMade()) return
            lastSelectedApp = app
    
            val coroutineScope = CoroutineScope(Dispatchers.Default)
            coroutineScope.launch { appsStartupFsm.submitEvent(AppSelected(app)) }
        }
    }
    AppsStartupFsm#submitEvent
    is a suspending function. Changing the runBlocking scope to be function level doesn’t seem to help. Is there something I’m missing with verification of suspending functions?
    s
    • 2
    • 7
  • b

    bjonnh

    01/21/2019, 2:44 AM
    I'm beginning to use tests in my Kotlin projects, is there any recommended framework (really basic needs for now)
    d
    b
    +2
    • 5
    • 13
  • e

    Eugen Martynov

    01/28/2019, 9:57 AM
    Hey guys, do you mark tests in the modules as internal classes?
    r
    • 2
    • 2
  • t

    Talon

    01/30/2019, 8:15 PM
    val commonTest by getting {
                dependencies {
                    implementation(kotlin("test-common"))
                    implementation(kotlin("test-annotations-common"))
                    implementation("org.jetbrains.kotlinx:kotlinx-serialization-runtime-common:0.9.1")
                }
            }
    I'm getting
    Unresolved reference: Test
    when I try and
    gradle check
    this multiplatform project. IntelliJ is able to find
    test-annotations-common
    at least enough to auto-import and stuff but something about the tests loses it?
    • 1
    • 1
  • t

    tddmonkey

    02/14/2019, 5:11 PM
    What do you mean? data generator?
    k
    • 2
    • 1
  • d

    dmcg

    02/15/2019, 1:33 PM
    I've released Minutest v1.0 today. Please check it out and let me know what you think. https://github.com/dmcg/minutest
    k
    c
    • 3
    • 4
  • b

    Ben

    02/22/2019, 6:16 AM
    Hi guys! I'm currently working on a REST application and try to do that with spring boot, webflux and the functional way with kotlin. With Annotations one could write unit tests by mocking the repository and call the methods of the controller. As the controller returns a Mono of the desired object, it was easily compared and asserted. In the functional way, my handler returns a Mono<ServerResponse>. When I debug it, the desired object is in that ServerResponse, but how to I get it's body? The interface doesn't offer a method for that?! I'm already using the WebTestClient for integration tests, but would now like to write some unit tests for the handler, just like I did for the controller earlier. Any help is appreciated! 🙂
    x
    d
    • 3
    • 3
  • p

    pablisco

    03/12/2019, 11:41 AM
    Thoughts on this? https://twitter.com/pablisc0/status/1105136620032921601?s=19 I thought @jw would like it specially since it doesn’t use Mockito but real lambdas 😁
    t
    • 2
    • 1
  • s

    Sam

    03/17/2019, 4:18 PM
    Is there a way to create automatic answers (with default returns) for a mocked object using mockk?
    o
    • 2
    • 15
  • h

    henrik

    03/28/2019, 5:26 AM
    Just thinking: how feasible would it be to implement the syntax and major features of Spock in Kotlin? http://spockframework.org/spock/docs/1.3/all_in_one.html
    r
    s
    • 3
    • 18
  • a

    AdalPari

    04/30/2019, 6:24 PM
    I'm trying to ignore a test, but it's still being run. Any help on how can I do it?
    -.txt
    m
    • 2
    • 3
  • l

    Lawik

    05/01/2019, 8:10 AM
    Does any have experience using
    Mockk
    I am trying to mock the following function
    fun <T> openAndCloseSession(handler: (Session) -> T): T {
        val session = HibernateUtil.sessionFactory.openSession()
        val res = handler(session)
        if (session.isOpen) {
            session.close()
        } else {
            println("[WARNING]: session closed by handler function: ${handler::class.java.enclosingMethod}, please consider omitting manually closing the session in the handler as it will be closed automatically at the end of the call")
        }
        return res
    }
    I want the mock to just call the provided
    handler
    (which I have mocked too). This is where I am currently at
    val session: Session = mockk()
    every { openAndCloseSession<Any>(any()) } answers {firstArg<(Session) -> Any>().invoke(session)}
    Sadly this doesn't work.
    t
    • 2
    • 10
  • r

    reik.schatz

    05/06/2019, 11:00 AM
    using junit5/assertJ is there a way for the compiler to figure out that something cannot be null? i.e.
    assertNotNull
    or
    assertThat(nullable).isNotNull
    won’t do the trick
    l
    r
    m
    • 4
    • 8
  • n

    nhaarman

    05/24/2019, 8:16 PM
    Ensure
    savePeriodicDump
    is non-final:
    any()
    returns
    null
    . If the
    savePeriodicDump
    method is final its code will be executed, meaning a
    null
    check will be performed on the parameter
    👍 1
    x
    • 2
    • 1
  • s

    samneirinck

    06/07/2019, 11:28 AM
    https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-test/#using-pausedispatcher-for-explicit-execution-of-runblockingtest can probably help here
    c
    • 2
    • 2
  • m

    Matej Drobnič

    06/10/2019, 5:42 AM
    Does anyone have any tips on how to properly manage large data literals in Kotlin tests? I'm writing unit tests for data mapping, so I have to do this: 1. Create test input data 2. Create expected output data 3. Perform mapping 4. Make sure output of the matches matches expected data Problem is that input and/or output data can be big data class with lots of nested data, which means that 95% of the code in the test function is just creating those data classes, creating a big mess. I could move this out of test methods, but every single test method has slightly different data (since it tests different thing), so I cannot have one universal constant with that data class in. I could move the data to resources as some kind of structure (such as JSON), but then I also have to build and maintain deserialization of that data for tests.
    d
    • 2
    • 4
  • m

    Mika Y Kost

    06/11/2019, 7:11 AM
    Hi, I'm new with kotlin, trying to decide whether I should use Junit or kotlinTest for unit testing. I'm not sure if this is the right forum to ask but, any help? 🙂
    a
    m
    +2
    • 5
    • 48
  • s

    svenjacobs

    06/12/2019, 8:56 AM
    Hi, is there an assertion library that nicely highlights diffs between expected and actual values? For instance when comparing two data classes
    actual shouldEqual expected
    . Currently I'm using Kluent but it just outputs the
    toString()
    values of both classes. If I want to find out which value(s) are actually different I have to do it manually.
    👍 1
    a
    m
    d
    • 4
    • 5
  • a

    Anthony f

    06/13/2019, 1:35 PM
    At bit of 👍 would be very great : https://jira.sonarsource.com/browse/SONARSLANG-353. Because today test cases are not push to SonarQube when it’s in koltin 😱
    m
    • 2
    • 2
  • r

    Rainer Schlonvoigt

    06/20/2019, 12:32 PM
    i'm probably blind, but is there somewhere a wiki that explains how to use
    kotlin-test-junit
    ?
    s
    h
    • 3
    • 2
  • b

    Badecx

    06/24/2019, 10:32 PM
    Hi people, I’m working with
    mockk
    and I have an
    every
    call that returns a list but I’m getting an error
    o.mockk.MockKException: Bad recording sequence. Please finalize every { ... } block with returns/answers/just Runs
    , I changed to
    answers {}
    and it worked perfectly and I don’t know why. Does anyone have ever go through this issue?
    l
    c
    • 3
    • 5
  • t

    tylerwilson

    06/26/2019, 9:59 PM
    This may be a basic question, but I need to set up test such that one is called first, and the remaining tests do not continue until the first one completes. They are all asynchronous/ coroutibe based methods...
    t
    • 2
    • 2
  • j

    Joan Colmenero

    07/04/2019, 1:44 PM
    I have a question if I have an
    attachView
    and
    detachView
    on my Presenter do I have to test these methods? Inside of the presenter I have the
    loadData
    and I have the unit tests for this
    loadData
    but then I have these methods and I don't know if I have to unit test those or not And then I have a repository that does this
    class CryptoListRepositoryImpl(var cryptoCurrencyService: CryptoCurrencyService) : CryptoListRepository {
        override fun getResultData(): Single<CryptoResponse> {
            return cryptoCurrencyService.getCryptoCurrency()
        }
    }
    do I have to unit test this
    getResultData()
    ? (edited) And then an use case
    class GetCryptoListUseCase @Inject constructor(var cryptoListRepository: CryptoListRepository) {
        fun execute(): Single<List<CryptoViewModel>> {
            return cryptoListRepository.getResultData().map {
                cryptoCurrencyMapper(
                    it
                )
            }
        }
    }
    I have to Unit test the
    mapper
    and the use case
    execute()
    ?
    t
    • 2
    • 4
  • m

    Manuel Lorenzo

    07/18/2019, 12:00 PM
    when executing
    testDevelopDebugUnitTest
    gradle task, I started to get random errors such as
    Missing method call for verify(mock) here:
    -> at com.nhaarman.mockitokotlin2.VerificationKt.verify(Verification.kt:72)
    
    Example of correct verification:
        verify(mock).doSomething()
    
    Also, this error might show up because you verify either of: final/private/equals()/hashCode() methods.
    Those methods *cannot* be stubbed/verified.
    Mocking methods declared on non-public parent classes is not supported.
    this only happen when the gradle task is executed, and if I ignore that test, then another one fails 🤔 I didn’t modify anything there, not in the injection or anything related.I tried changing the mockito-kotlin version, the mockito-core version, upgrading gradle, upgrading the gradle android plugin..
    t
    • 2
    • 8
Powered by Linen
Title
m

Manuel Lorenzo

07/18/2019, 12:00 PM
when executing
testDevelopDebugUnitTest
gradle task, I started to get random errors such as
Missing method call for verify(mock) here:
-> at com.nhaarman.mockitokotlin2.VerificationKt.verify(Verification.kt:72)

Example of correct verification:
    verify(mock).doSomething()

Also, this error might show up because you verify either of: final/private/equals()/hashCode() methods.
Those methods *cannot* be stubbed/verified.
Mocking methods declared on non-public parent classes is not supported.
this only happen when the gradle task is executed, and if I ignore that test, then another one fails 🤔 I didn’t modify anything there, not in the injection or anything related.I tried changing the mockito-kotlin version, the mockito-core version, upgrading gradle, upgrading the gradle android plugin..
t

tddmonkey

07/18/2019, 12:02 PM
Grasping at straws - are you running parallel?
m

Manuel Lorenzo

07/18/2019, 12:04 PM
uh let me see
yes I am
t

tddmonkey

07/18/2019, 12:05 PM
try it without
m

Manuel Lorenzo

07/18/2019, 12:07 PM
I have now
org.gradle.jvmargs=-Xmx4608M
android.enableD8=true
android.useAndroidX=true
android.enableJetifier=true
org.gradle.parallel=false
kotlin.parallel.tasks.in.project=true
kapt.use.worker.api=true
android.enableUnitTestBinaryResources=true
kapt.incremental.apt=true
I deactivated
org.gradle.parallel=false
but still failing
t

tddmonkey

07/18/2019, 12:36 PM
That’s me out of ideas then 😕
m

Manuel Lorenzo

07/18/2019, 12:43 PM
and that makes the two of us 🙂 the whole day yesterday and still today trying to fix this
View count: 5