简体   繁体   中英

Is there a way to mock the invocation of a secondary constructor of a Kotlin data class using mockk

From the documentation of mockk.io regarding the mocking capabilities of constructors I can see the following:

class MockCls(private val a: Int = 0) {
  constructor(x: String) : this(x.toInt())  
  fun add(b: Int) = a + b
}

mockkConstructor(MockCls::class)

every { constructedWith<MockCls>().add(1) } returns 2

As far as I understood it is possible to mock the construction of an object and get a result for an executed method.

What I would like to have is eg the following

data class MyDataClass(val first: String) {

    constructor(anotherDataClass: AnotherDataClass) : this(
        first = anotherDataClass.second
    )
}

data class AnotherDataClass(val second: String) 

mockkConstructor(MyDataClass::class)

every { constructedWith<MyDataClass>() } returns mockk<MyDataClass>

or

every { anyConstructed<MockCls>() } returns mockk<MyDataClass>

In the end, I want to bypass the construction and directly return a constructed mock and not first execute a method and return the result.

Avoiding constructor execution while mocking not currently (<=1.12.0) possible by design ( https://github.com/mockk/mockk/issues/515 )

If you really want to capture instance while doing constructor mocking, you can get away with this:

val myMockedInstance: MyClass = MockKGateway.implementation().constructorMockFactory.mockPlaceholder(
            MyClass::class,
            args = arrayOf<Matcher<*>>(
                EqMatcher(dummyParamOfMine)
            ) as Array<Matcher<*>>
        )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM