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
  • f

    Florian Walther (live streaming)

    01/01/2022, 12:03 PM
    I'm trying to test a LiveData using the
    getOrAwaitValue
    helper function from the Google samples. But this LiveData is coming from a
    MutableStateFlow
    using
    asLiveData
    . There seems to be a race condition and I am not getting a value in my test. I've tried passing the
    StandardTestDispatcher
    to
    asLiveData
    but it didn't change anything.
    • 1
    • 1
  • n

    nikolaymetchev

    02/14/2022, 1:32 PM
    Hi, I am trying to see if we can use the Intellij coverage agent with kover to replace jacoco. We currently use Jenkins and sonarqube to display the coverage results. The Jenkins jacoco plugin is looking for a *.exec file but when I point it to the *.ic file it doesn’t seem to be compatible. Is this correct?
    e
    m
    • 3
    • 2
  • c

    Christoph Beylage

    03/22/2022, 4:56 PM
    Hello guys, we have a little problem with mocking in out unit tests. It looks a bit like an error per design in kotlin. but actually, i cant believe this 😄 we tried mockk and mockito regarding this and both result in the same problem. imagine we have an instance of the following class:
    data class AppConfig(
        var smtp = SmtpConfig(
                enabled = false
                host = "test",
                port = 12345,
                useStartTLS = true,
                fromName = "test",
                from = "<mailto:test@test.de|test@test.de>"
                user = ""
                password = ""
        )
    )
    
    val classInstance = AppConfig()
    what I want to do in one of our tests is to mock the value of smtp. What I did - here for example with mockito - was the following:
    val spy = Mockito.spy(classInstance)
    Mockito.`when`(spy.smtp).thenReturn(SmtpConfig(true)). //true is the enabled flag in this case, so the rest should be null
    What Mockito and Mockk are doing in this case is to mock the get method behind that property. This can be verified by starting the debugger right in the line after the Mockito.\`when\` expression. The field is exactly like initialized above and when I click the getter in the debugger I get the result from spy.smtp, as you can see in the screenshot. I can understand why this happens, but kotlin simply does not use the getters of those properties why the tests wont work. So long text, simple question: Any idea how to fix this? Everything I found was a github issue from mockk with exactly the same problem and that has been closed because to support this a major rebuild would be necessary.
    j
    • 2
    • 35
  • m

    mbonnin

    03/25/2022, 12:31 PM
    Is it possible to benchmark some code in a way that's not bound to a specific machine? I'd like to monitor performance regressions in CI but cannot make any assumption about what type of VM runs the code. Is something like this possible?
    m
    s
    • 3
    • 49
  • r

    Rak

    04/01/2022, 9:48 AM
    Hi, I am writing some unit tests for an
    object
    class. Is there a way to “reset” the instance? It keeps its state between tests.
    m
    m
    • 3
    • 2
  • m

    muthuraj

    04/19/2022, 11:59 AM
    Hi, I updated the Kotiln version and migrating to
    runTest
    alternate from
    runBlocking
    and I'm facing an issue in testing a specific use case. Here is a simplified version of the test case I want to run.
    @Test(expected = NullPointerException::class)
        fun test() = runTest {
    
            //In my actual code, I'm testing a ViewModel which uses viewModelScope to launch a coroutine
            //and it will throw an exception for a specific case.
            val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
            scope.launch {
                throw NullPointerException("error")
            }
        }
    • 1
    • 1
  • m

    marzelwidmer

    05/09/2022, 8:15 AM
    Hello I hope I am on the right channel… We have some issues with
    Sonar
    coverage. and
    value
    classes.. and
    init
    function. it looks like the coverage ist not right on sonar. we use the
    jacoco
    maven plugin version
    0.8.7
    m
    • 2
    • 1
  • v

    v79

    06/10/2022, 6:30 AM
    I'm migrating a program to Kotlin 1.6, and from build.gradle to build.gradle.kts. I'm using
    spek
    and
    mocck
    for testing. I'm getting a gradle error and wondered if someone could help me understand what it means?
    Execution failed for task ':compileTestKotlin'.
    > Could not resolve all files for configuration ':testCompileClasspath'.
       > Could not resolve org.jetbrains.kotlin:kotlin-test-junit5:1.6.21.
         Required by:
             project :
          > Module 'org.jetbrains.kotlin:kotlin-test-junit5' has been rejected:
               Cannot select module with conflict on capability 'org.jetbrains.kotlin:kotlin-test-framework-impl:1.6.21' also provided by [org.jetbrains.kotlin:kotlin-test-junit:1.6.21(junitApi)]
       > Could not resolve org.jetbrains.kotlin:kotlin-test-junit:1.6.21.
         Required by:
             project : > io.insert-koin:koin-test:3.2.0 > io.insert-koin:koin-test-jvm:3.2.0
          > Module 'org.jetbrains.kotlin:kotlin-test-junit' has been rejected:
               Cannot select module with conflict on capability 'org.jetbrains.kotlin:kotlin-test-framework-impl:1.6.21' also provided by [org.jetbrains.kotlin:kotlin-test-junit5:1.6.21(junit5Api)]
    From my build.gradle.kts file, I have the following test configuration:
    dependencies {
    // ...
    // testing
    	testImplementation("io.insert-koin:koin-test:$koin_version")
    //	testImplementation("org.jetbrains.kotlin:kotlin-test:$kotlin_version")
    	testImplementation("org.jetbrains.kotlin:kotlin-test-junit5:$kotlin_version")
    	testImplementation("org.spekframework.spek2:spek-dsl-jvm:$spek_version")
    	testRuntimeOnly("org.spekframework.spek2:spek-runner-junit5:$spek_version")
    	testImplementation("io.mockk:mockk:$mockk_version")
    }
    
    tasks.test {
    	useJUnitPlatform {
    		includeEngines("spek2")
    	}
    }
    
    tasks.withType<KotlinCompile> {
    	kotlinOptions.jvmTarget = "11"
    }
    Just trying to make sense of the error really.
    • 1
    • 1
  • z

    zak.taccardi

    06/16/2022, 9:07 PM
    does
    kover
    support
    src/androidTest
    ?
  • t

    tylerwilson

    06/17/2022, 1:56 PM
    Any good examples of unit test setup for a multiplatform module, including jvm, android, ios, watchos, macos and optionally js? Thanks!
  • m

    Matthias Geisler

    06/21/2022, 8:24 PM
    New Version of KMock is out: https://github.com/bitPogo/kmock/releases
  • m

    Matthias Geisler

    06/21/2022, 8:24 PM
    And KFixture https://github.com/bitPogo/kfixture
    k
    • 2
    • 2
  • p

    Piotr Krzemiński

    07/05/2022, 9:31 AM
    hi folks, I'm looking for an equivalent of PITest for mutation testing, for Kotlin. PITest which is optimized for Java doesn't give great results for Kotlin, and this plugin was deprecated. The author recommends a commercial tool called arcmutate. Any thoughts, experience to share?
    c
    • 2
    • 2
  • i

    igor.wojda

    07/19/2022, 9:51 AM
    Hey Assuming we need to advance coroutine time using
    advanceUntilIdle()
    method. I wonder where this method belongs in BDD (
    When
    or
    Then
    block?)
    @Test
        fun `test something`() = runTest {
            // given
            setup code
    
            // when
            subject.init()
            advanceUntilIdle()
    
            // then
            verify something
        }
    or
    @Test
        fun `test something`() = runTest {
            // given
            setup code
    
            // when
            subject.init()
    
            // then
            advanceUntilIdle()
            verify something
        }
  • m

    mbonnin

    07/28/2022, 2:04 PM
    CanI have the JS Promise handling of
    runTest {}
    but not the delay-skipping behaviour? Delays are a part of the behaviour I want to test
    e
    m
    t
    • 4
    • 5
  • d

    dmcg

    09/09/2022, 8:56 PM
    Stop Using JUnit BeforeEach!

    https://youtu.be/cs2Wu9Co-2s▾

    c
    x
    • 3
    • 15
  • d

    dmcg

    09/17/2022, 8:13 AM
    How to Test Shared Behaviour with JUnit Contracts

    https://youtu.be/i_RqslILYtg▾

  • d

    dmcg

    09/20/2022, 10:57 AM
    A New Way to Manage JUnit Test State in Kotlin

    https://youtu.be/PnbV1rVI62I▾

    m
    m
    • 3
    • 2
  • c

    Chih Wei Lin

    09/24/2022, 2:54 PM
    Is it good to test all error case in one test func? for example:
    @Test
    fun `my error test`() {
        every { apiManager.foo() }.returnsMany(
            Observable.just(Response.error("Error A".toResponseBody())),
            Observable.just(Response.error("Error B".toResponseBody())),
            Observable.just(Response.error("Error C".toResponseBody())),
        )
    
        repeat(3) { presenter.bar() }
    
        verifyOrder {
            view.showErrorA()
            view.showErrorB()
            view.showErrorC()
        }
    }
    c
    • 2
    • 2
  • z

    Zach Klippenstein (he/him) [MOD]

    10/04/2022, 3:09 AM
    Has anyone managed to get the TestParameterInjector constructor injection working with kotlin value classes? It looks like Kotlin generates an additional constructor when there’s a value class in the constructor parameter list, which confuses the library only expecting a single constructor.
    e
    • 2
    • 7
  • r

    Reece H. Dunn

    10/22/2022, 6:10 AM
    Hi, are there any plans to add
    @DisplayName
    and
    @Nested
    to the kotlin.test core annotations list? I find these annotations useful when writing JUnit tests in Kotlin/JVM.
    @DisplayName
    -- Because Kotlin/JS does not support spaces in backtick function names, and Kotlin/native does not allow parenthesis having a
    @DisplayName
    annotation allows for a more readable test name (and the ability to specify the class description).
    @Nested
    -- I often find it useful to use this in my tests, especially to group different partitions or use cases for the thing under test. For example, testing a "to list" or "list of" method with zero, one, and many items.
  • m

    Manuel Lorenzo

    10/22/2022, 6:49 PM
    I’m implemented the Paging 3 library and I’d like to test my repository. I’ve seen the Paging 3 testing webpage but there’s only theory about the repository tests. My repository looks like this:
    class RepositoriesRepositoryImpl @Inject constructor(
        @IoCoroutineDispatcher private val ioCoroutineDispatcher: CoroutineDispatcher,
        private val service: GithubService,
        private val database: RepositoriesDatabase
    ) : RepositoriesRepository {
        @OptIn(ExperimentalPagingApi::class)
        override suspend fun fetchRepositories() = withContext(ioCoroutineDispatcher) {
            return@withContext Pager(config = PagingConfig(
                pageSize = NETWORK_PAGE_SIZE, enablePlaceholders = false
            ),
                remoteMediator = GithubRemoteMediator(ioCoroutineDispatcher, service, database),
                pagingSourceFactory = { database.repositoriesDao().allRepositories() }).flow
        }
    
        companion object {
            const val NETWORK_PAGE_SIZE = 10
        }
    }
    And this is my test class:
    @ExperimentalCoroutinesApi
    class RepositoriesRepositoryTest {
        private lateinit var sut: RepositoriesRepository
        private val testDispatcher = UnconfinedTestDispatcher()
        private val fakeGithubService: GithubService = mock {
            onBlocking { fetchRepos(any(), any()) } doSuspendableAnswer {
                Response.success((listOf()))
            }
        }
        private val inMemoryDatabase = Room.inMemoryDatabaseBuilder(
            ApplicationProvider.getApplicationContext(), RepositoriesDatabase::class.java
        ).build()
    
        @Before
        fun setup() {
            sut = RepositoriesRepositoryImpl(testDispatcher, fakeGithubService, inMemoryDatabase)
        }
    
        @Test
        fun test1() = runTest {
            sut.fetchRepositories().test {
                val item: PagingData<Repository> = awaitItem()
                assertNull(item)
            }
        }
    }
    What I’m trying is to assert the content of the
    PagingData
    , just to see that it contains whatever number repository I’m passing in the test expectation. How could I do this? Thanks!
  • d

    Davide Giuseppe Farella

    10/27/2022, 5:11 PM
    Hello everybody, I have a model like
    sealed interface AffectsA
    sealed interface AffectsB
    
    sealed interface Action {
    
      object Act1 : Action, AffectsA
      object Act2 : Action, AffectsA, AffectsB
      object Act3 : Action, AffectsB
    }
    and a class like
    class Reducer(
      private val subReducer1: X,
      private val subReducer2: Y
    ) {
    
      fun reduce(state: State, action: Action): State =
        when (action) {
          is Act1 -> state.copy(
            a = subReducer1.reduce(state.a, action)
          )
          Act2 -> state.copy(
            a = subReducer1.reduce(state.a, action),
            b = subReducer2.reduce(state.b, action)
          )
          Act3 -> state.copy(
            b = subReducer2.reduce(state.b, action)
          )
        }
    }
    I wanna test that for every action, the correct sub-reducer is called. Something like
    reducer.reduce(someState, Act2)
    verify {
      subReducer1.reduce(someState.a, Act2)
      subReducer2.reduce(someState.b, Act2)
    }
    
    /// 
    
    reducer.reduce(someState, Act3)
    verify {
      subReducer1 wasNot Called
      subReducer2.reduce(someState.b, Act2)
    }
    I usually like to use
    org.junit.runners.Parameterized
    for these cases, but I wanna ensure that all the cases are covered, a.k.a. every sub-type of Action. Got any idea?
    d
    • 2
    • 3
  • r

    radzio

    11/14/2022, 1:24 PM
    Does anyone have problems with mocking with Kotlin 1.7.20 https://github.com/mockito/mockito/issues/2777 ?
  • k

    kevin.cianfarini

    11/15/2022, 5:32 PM
    Is the kotlin team planning on an analog to Junit timeout rules? I currently have a mpp test suite where the failure mode is a synchronous infinite loop, which I would like to fail after like 100ms.
  • p

    Peter Farlow

    12/21/2022, 10:26 PM
    I’m working on a class that handles performing a suspending task (logging the user in) as well as maintaining a SharedFlow so other components can be alerted when the task is performed:
    class ExampleClass(
        private val loginApi: LoginApi,
        externalScope: CoroutineScope,
    ) {
        private val _loginFlow = MutableSharedFlow<String>()
    
        val loginFlow = _loginFlow.shareIn(externalScope, SharingStarted.Lazily)
    
        suspend fun performLogin(): String {
            val result = loginApi.performLogin()
            _loginFlow.emit(result)
            return result
        }
    }
    
    interface LoginApi {
        suspend fun performLogin(): String
    }
    I’ve written a test case for this:
    class ExampleClassTest {
    
        private val mockApi = mockk<LoginApi> {
            coEvery { performLogin() } returns "hello"
        }
    
        private val testCoroutineScheduler = UnconfinedTestDispatcher()
        private val testScope = TestScope(testCoroutineScheduler)
    
        @Test
        fun `this test passes`() = runTest(testCoroutineScheduler) {
            val exampleClass = ExampleClass(mockApi, testScope)
            expect("hello") {
                exampleClass.performLogin()
            }
        }
    }
    Can anyone help me understand why calling runTest directly on my TestScope causes this test case to fail with an eventual UncompletedCoroutinesError? The error message says the test coroutine is not completing, and also that there’s an active child job.
    @Test
        fun `this test times out`() = testScope.runTest {
            val exampleClass = ExampleClass(mockApi, testScope)
            expect("hello") {
                exampleClass.performLogin()
            }
        }
    • 1
    • 1
  • p

    Peter Farlow

    12/22/2022, 3:18 PM
    I’ve just been informed for cases like this, you’re supposed to use
    TestScope.backgroundScope
    . Perhaps this example is more correct:
    class ExampleClassTest {
        private val mockApi = mockk<LoginApi> { coEvery { performLogin() } returns "hello" }
        private val testCoroutineScheduler = UnconfinedTestDispatcher()
        private val testScope = TestScope(testCoroutineScheduler)
    
        @Test
        fun `this test passes`() = testScope.runTest {
            val exampleClass = ExampleClass(mockApi, testScope.backgroundScope)
            expect("hello") {
                exampleClass.performLogin()
            }
        }
    }
    • 1
    • 1
  • k

    Kwabena Berko

    01/21/2023, 1:40 AM
    Hi @Gabriel Feo Did you find a solution for this?
    g
    • 2
    • 1
  • d

    diego-gomez-olvera

    02/20/2023, 2:32 PM
    I find nice that
    kotlin.test
    besides convenient functions like assertFailsWith, it has inspections to guide devs to use the proper one, which will give more useful error messages
  • a

    arekolek

    02/27/2023, 8:21 PM
    Let me share this here in case anybody else finds this useful https://kotlinlang.slack.com/archives/C0BJ0GTE2/p1668539856830919 (I'm not associated with the library, I was just looking for something like this and was happy to find it exists) BTW maybe you know of anything else similar to this?
Powered by Linen
Title
a

arekolek

02/27/2023, 8:21 PM
Let me share this here in case anybody else finds this useful https://kotlinlang.slack.com/archives/C0BJ0GTE2/p1668539856830919 (I'm not associated with the library, I was just looking for something like this and was happy to find it exists) BTW maybe you know of anything else similar to this?
View count: 5