Dan
Dan

Reputation: 12665

How can I use MockK to return a particular value from a constructor?

I'm writing some Kotlin tests, and I want to mock the return value of a particular method of an object that's constructed.

Right now I have

every{
   anyConstructed<FooMaker>.execute(fooId)
} returns testFoo

This compiles, but when run fails with the exception:

io.mockk.MockKException: to use anyConstructed<T>() or constructedWith<T>(...) first build mockkConstructor<T>() and 'use' it

This example from the documentation works just fine:

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

What does this error mean? How do I build mockkConstructor<Foo> and 'use' it?

Upvotes: 0

Views: 115

Answers (1)

Dan
Dan

Reputation: 12665

In general, you need to call mockkConstructor before the every block:

mockkConstructor(Foo::class)
every {
    anyConstructed<Foo>().execute(fooId)
} returns testFoo

This creates a mock constructor for Foo that the every block can use.

See the documentation here.

Upvotes: 1

Related Questions