English 中文(简体)
I am trying to use mockk anyConstructed but ending with Missing calls inside every { ... } block
原标题:
  • 时间:2021-12-23 07:36:11
  •  标签:
  • kotlin
  • mockk

I am trying to return an object whenever a new object of a class is being created.

I have tried using anyConstructed with a spyk or even mockk object of PredictionCheckFunction

every { anyConstructed<PredictionCheckFunction>() } answers { predictionCheckFunction }

It results in the following error on the above line

io.mockk.MockKException: Missing calls inside every { ... } block.

In Mockito I would do something like this

whenNew(PredictionCheckFunction.class).withNoArguments().thenReturn(predictionCheckFunction);

I want to make sure that every creation of PredictionCheckFunction results in an object of predictionCheckFunction

The example in this Question How to mock a new object using mockk allows me to only run a function on a mock object but not return one already created like above Mockito example thenReturn(predictionCheckFunction); -

Example in referred SO Question -

mockkConstructor(Dog::class)
every { anyConstructed<Dog>().bark() }

Any help on how to do this while creation of a new object, is appreciated.

问题回答

Based on the official tutorial, it seems we can t assign a mock instance to any constructed class instance, like:

mockkConstructor(TargetCls::class)
every { anyConstructed<TargetCls>() } returns mockk()

There s no example usage like the above codes. And that would case an exception...

However, you can write this, as the official tutorial states:

class MockCls {
  fun add(a: Int, b: Int) = a + b
}

mockkConstructor(MockCls::class)

every { anyConstructed<MockCls>().add(1, 2) } returns 4

assertEquals(4, MockCls().add(1, 2)) // note new object is created

verify { anyConstructed<MockCls>().add(1, 2) }

See the tutorial.





相关问题
Exposed runs query on all HikariCP open connections

I m running a Ktor server with a PostgreSQL database and just set up the JetBrains Exposed ORM framework with HikariCP for connection pooling (per the recommendation in the Ktor documentation). My ...

SQLite Kotlin issue - no database

I am trying to create boardgamegeek APIs based app in AndroidStudio, however from unknown reason I m getting my database created with no columns. Here s Logical log: (1) no such table: games in "...

Flutter App cannot be installed on Android TV

I m building a Flutter app that should support Android TV and Mobile devices. Despite Google Play shows that it is supported, I cannot install app on my MiBox device. While trying to install it, both ...

热门标签