Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock a new object using mockk

Tags:

kotlin

mockk

I'm trying to write unit tests using mockk.

I'm trying to figure out how to mock a new instance of an object.

For example, using PowerMockito we would write:

PowerMockito.whenNew(Dog::class.java).withArguments("beagle").thenReturn(mockDog)

If the expected result of my test is mockDog, I want to be able to assert that it equals my actualResult:

assertEquals(mockDog, actualResult)

How would I accomplish this using mockk?

Thanks in advance.

like image 291
Scott Avatar asked Oct 10 '18 14:10

Scott


1 Answers

Using mockkConstructor(Dog::class) you can mock constructors in MockK. This will apply to all constructors for a given class, there is no way to distinguish between them.

The mocked class instance can be obtained by using anyConstructed<Dog>(). You can use that to add any stubbing and verification you need, such as:

every { anyConstructed<Dog>().bark() } just Runs
like image 200
NotWoods Avatar answered Sep 17 '22 15:09

NotWoods