4

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.

Akshay Hazari
  • 3,186
  • 4
  • 48
  • 84

1 Answers1

0

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.

Joy Wen
  • 3
  • 3
  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jun 06 '23 at 09:11