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
mockk
  • p

    poohbar

    05/28/2018, 2:30 PM
    my big picture tests are integration tests that don't use mocking at all
    d
    • 2
    • 1
  • o

    oleksiyp

    06/04/2018, 9:30 PM
    New MockK 1.8.1 released. Added constructor mocking and deprecated mocking via scopes
    👏🏼 2
    i
    • 2
    • 1
  • t

    thatadamedwards

    06/08/2018, 9:36 PM
    I have this little snippet:
    val (_, _, result) = myUrlString.httpPost()
                .header("Content-Type" to "application/json", "Authorization" to "Bearer $authToken")
                .body(jacksonObjectMapper().writeValueAsString(message))
                .responseString()
    
            if (result is Result.Failure) {
                val errorMessage = result.error.response.responseMessage
    
                throw BadRequestException(errorMessage)
            } else {
                return true
            }
    d
    • 2
    • 3
  • d

    dave08

    06/10/2018, 5:37 PM
    How do I mock
    resolve
    extension from Kotlin stdlib on a File? I tried this, but it still seems to call the Kotlin code:
    fun mockFile() = mockk<File>().apply {
    	every { resolve(any<File>()) } answers { mockk<File>(relaxed = true).apply {
    		every { path } returns "this.txt"
    	} }
    }
    
    // Gives
    path must not be null
    java.lang.IllegalStateException: path must not be null
    	at kotlin.io.FilesKt__FilePathComponentsKt.isRooted(FilePathComponents.kt:81)
    	at kotlin.io.FilesKt__UtilsKt.resolve(Utils.kt:400)
    g
    o
    • 3
    • 2
  • g

    ghedeon

    06/10/2018, 5:41 PM
    just to understand it clear, when it says "static mocks in mockk" it actually refers to extension functions? Or, is it also possible to mock something like
    Html.fromHtml()
    ?
    o
    • 2
    • 3
  • g

    ghedeon

    07/19/2018, 2:09 PM
    awesome, exactly what I was looking for. The only bummer is import conflicts with assertion library (atrium in my case).
    Assert
    is quite popular on the assertion market). Thank you!
    d
    • 2
    • 1
  • p

    poohbar

    08/09/2018, 2:09 PM
    Sometimes one of my tests fails with
    ConcurrentModificationException
    .. the tests looks kind of like this:
    service.doSomething()
    
    verify { mock1.aMethod() }
    verify { mock2.aMethod() }
    verify { mock3.aMethod() }
    verify { mock4.aMethod() }
    verify { mock5.aMethod() }
    verify { mock6.aMethod() }
    it throws the exception on the first
    verify
    .. any clue what it could mean?
    o
    • 2
    • 1
  • q

    quiqua

    08/20/2018, 9:58 AM
    Is it possible to create a
    spyk
    on a:
    object GeometryValidation {
    
        fun isPoint(coordinates: Position): ValidationResult = coordinates.validate()
        fun isLineString(coordinates: List<Position>): ValidationResult {
           coordinates.forEach { isPoint(it) }
           ....
        }
        private fun ...
    }
    and then verify that
    isPoint
    has been called when calling
    isLineString
    ?
    o
    • 2
    • 4
  • o

    oleksiyp

    10/05/2018, 9:08 AM
    Yeah Ive seen it. Thank you. Looks good to me. Worth sharing in slack #feed, reddit, kotlin forum. I usally do that. But actually up to you how to do marketing for it
    d
    • 2
    • 3
  • p

    poohbar

    10/05/2018, 6:52 PM
    The top minds of Kotlin community answered question: "How do you mock final classes" with "Legacy PowerMock usage or pull the class into an interface" wtf. 😢 😢 😢 @elizarov I summon you to learn about this amazing project because I saw you nodding to that dumb answer! 😄
    👍 3
    e
    • 2
    • 2
  • o

    oleksiyp

    10/10/2018, 10:26 AM
    Yes, clear is suggested if you want to return back default behavior, otherwise next mockkStatic will clear it
    🙂 1
    d
    • 2
    • 30
  • o

    oleksiyp

    10/17/2018, 7:47 PM
    Hi @Jonathan Walsh. The initial design allows doing concurrency. There was a bug on concurrency and it was fixed. So I know that people do parallel tests.
    j
    • 2
    • 2
  • g

    gildor

    10/18/2018, 2:17 AM
    Is there any way to emulate verifyNoInteractions from mockito? Because I found that I missed this verification method in some cases
    o
    d
    • 3
    • 12
  • h

    Hexa

    10/25/2018, 1:25 PM
    does anyone know if
    <http://mockk.io|mockk.io>
    has an equivalent of this method
    any(Class<T> type)
    which is from Mockito https://static.javadoc.io/org.mockito/mockito-core/2.11.0/org/mockito/ArgumentMatchers.html. I can't seem to find any equivalent so not sure what to use instead
    o
    • 2
    • 3
  • h

    Hexa

    10/26/2018, 2:46 PM
    my mock is returning another mock, is that a sign of bad code / code smell? the thing is I been stuck for a day trying to figure out a better way to do it but I can't seem to find any alternatives
    o
    • 2
    • 3
  • h

    Hexa

    10/28/2018, 10:45 AM
    anyone knows if
    any<T>()
    is the same as
    any()
    in this example?
    o
    • 2
    • 2
  • u

    uhe

    10/30/2018, 2:14 PM
    Anybody else get
    Failed to resolve: org.jetbrains.kotlin:kotlin-reflect:1.3.0-rc-80
    when using
    io.mockk:mockk:1.8.9.kotlin13
    ?
    m
    o
    • 3
    • 8
  • g

    Gokul

    10/31/2018, 5:11 AM
    Hey everyone, I am curious to understand why
    mockkObject()
    does not have a
    clearObjectMock()
    method ? And how it is able to reset itself after every test?
    o
    • 2
    • 3
  • j

    jobot0

    10/31/2018, 1:58 PM
    Hey everyone not sure how
    capture(slot)
    should work here.
    val obj = ExtendedObjBecauseImTestingOnAndroidUnderP(someStuff, someOtherStuff)
    val objSpy = spyk(obj)
    val slot = slot<ParamType>()
    every {
      obj.methodWhichSouldBePrivate(capture(slot), otherStuff))
    } just Runs
    Why am I getting this issue
    left matchers: [slotCapture<ParamType>()]
    ?
    o
    • 2
    • 2
  • h

    Hexa

    10/31/2018, 3:22 PM
    does mockk have an equivlalent of
    Mockito.anyBoolean()
    ??
    d
    • 2
    • 1
  • p

    poohbar

    11/06/2018, 4:11 PM
    @oleksiyp Hi Oleksiy, I was wondering, are the mocks generated by Mockk final? And if so why? Can they be made non-final?
    o
    • 2
    • 6
  • p

    poohbar

    11/08/2018, 1:20 PM
    @thanksforallthefish Cool! I am going to try it. It didn't even cross my mind to mess with byte buddy. For some reason I thought it was some super hidden JDK internal class.
    t
    o
    • 3
    • 3
  • r

    robin

    11/14/2018, 10:30 PM
    Hi all, is there a way to check that there were no other interactions with a mock than the ones checked via
    verify
    ? I'm currently switching from Mockito to MockK and am wondering what to do with my
    verifyNoMoreInteractions(mock)
    calls.
    g
    • 2
    • 2
  • m

    MrNiamh

    11/15/2018, 11:23 AM
    How have people found using Mockk compared to mockito-kotlin?
    g
    • 2
    • 4
  • a

    Anthony f

    11/28/2018, 4:24 PM
    @oleksiyp Hi, I let you a comment on Github, I think we misunderstand each others. Please come back to me for a tchat, if you think this is easier.
    o
    • 2
    • 19
  • m

    MrNiamh

    11/29/2018, 6:21 PM
    I'm trying to mock a specific instance, but doesn't seem to work. E.g.: val myData = MyData(min = 3, max = 4) val myMock = mockk<SomeObject>.apply { every { someFunc(myData) } returns SOME_ID } Inside my SomeObject, it actually creates a MyData with the values 3 and 4, so it's not the exact same instance. So if I change myData to any() in the mock, then it works. Essentially, how do I check against an object that would be equal, not the same instance?
    💯 1
    o
    • 2
    • 3
  • o

    oleksiyp

    11/29/2018, 7:13 PM
    By default equals is used
    m
    • 2
    • 1
  • m

    maxmello

    12/03/2018, 4:01 PM
    Hello everybody, I want to test code that calls a repository, which I have mocked. I want the
    repository.save(entity)
    method to just return whatever is passed into it. I thought that
    Slot
    would be the correct way of doing this, but …
    val slot = slot<Entity>()
    every { repository.save(capture(slot)) } answers { slot.captured }
    … does not work, because the slot.captured is lateinit and not initialized during initialization of the mocks. Am I missing something or is this not possible with mockK?
    r
    o
    • 3
    • 9
  • j

    jdiaz

    12/04/2018, 12:39 AM
    Hello, is it possible to call a private method when spying an object with answers?
    every { obj.method() } answers { mock["privateMethod"](); whatever; }
    o
    • 2
    • 1
  • t

    tKw

    12/12/2018, 4:02 PM
    Hello all, has anyone had luck mocking Exposed with MockK? The team I am on have been trying to verify that a select query (or insert, update, etc.) is called. I will add the minified code I have setup (similar to our production code) and what we have so far for testing which is not working.
    • 1
    • 2
Powered by Linen
Title
t

tKw

12/12/2018, 4:02 PM
Hello all, has anyone had luck mocking Exposed with MockK? The team I am on have been trying to verify that a select query (or insert, update, etc.) is called. I will add the minified code I have setup (similar to our production code) and what we have so far for testing which is not working.
import com.zaxxer.hikari.HikariConfig
import com.zaxxer.hikari.HikariDataSource
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.jetbrains.exposed.dao.IntIdTable
import org.jetbrains.exposed.sql.Database
import org.jetbrains.exposed.sql.ResultRow
import org.jetbrains.exposed.sql.Transaction
import org.jetbrains.exposed.sql.selectAll
import org.jetbrains.exposed.sql.transactions.transaction
import kotlin.coroutines.CoroutineContext


class DatabaseConnection(config: HikariConfig) {
    private val dispatcher: CoroutineContext = Dispatchers.Default
    private val connection: Database = Database.connect(HikariDataSource(config))

    suspend fun <T> query(transaction: Transaction.() -> T) =
        withContext(dispatcher) {
            transaction(db = connection, statement = transaction)
        }
}

interface DatabaseConnectionProvider {
    suspend fun <T> query(transaction: (Transaction.() -> T)): T
}

object DatabaseTest : DatabaseConnectionProvider {
    val config = HikariConfig().apply {
        driverClassName = "org.postgresql.Driver"
        jdbcUrl = "jdbc:<postgresql://localhost:5432/exposed>"
        username = "exposed"
        password = "exposed"
        maximumPoolSize = 3
        isAutoCommit = false
        transactionIsolation = "TRANSACTION_REPEATABLE_READ"
    }

    private val connection: DatabaseConnection = DatabaseConnection(config)

    override suspend fun <T> query(transaction: (Transaction.() -> T)) = connection.query(transaction)
}

object Peeps : IntIdTable("peeps") {
    data class Peep(val name: String, val role: String)

    val name = text("name")
    val role = text("role")

    fun toPeep(row: ResultRow): Peep = Peep(
        row[Peeps.name],
        row[Peeps.role]
    )
}

suspend fun main() {
    DatabaseTest.query {
        Peeps.selectAll().orderBy(Peeps.id).map { Peeps.toPeep(it) }.forEach { println("${it.name} - ${it.role}") }
    }
}
import io.kotlintest.specs.DescribeSpec
import io.mockk.*
import kotlinx.coroutines.runBlocking
import org.jetbrains.exposed.sql.Transaction
import org.jetbrains.exposed.sql.selectAll
import org.jetbrains.exposed.sql.statements.InsertSelectStatement

class MainTests: DescribeSpec({
    describe("test migrateDatabase") {
        it("") {
            coEvery {
                DatabaseTest.query(any<Transaction.() -> Unit>())
            } returns mockk()

            runBlocking {
                DatabaseTest.query {
                    Peeps.selectAll().map { Peeps.toPeep(it) }.forEach { println(it.name) }
                }
            }

            coVerify {
                DatabaseTest.query { any<InsertSelectStatement>() }
            }
        }
    }
})
View count: 8