10

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.

Scott
  • 1,263
  • 1
  • 12
  • 23

2 Answers2

3

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
NotWoods
  • 686
  • 4
  • 13
  • This is good information on how to handle test expectations, however it does not answer my question of how to perform asserts. If the class under test returns an instantiated object (actualResult), I'd like to be able to assert that it equals the mock object created (expectedResult). – Scott Sep 16 '20 at 10:53
  • When I add this gives me some error `io.mockk.MockKException: to use anyConstructed() first build mockkConstructor() and 'use' it` Can we add something like this as well to verify - `verify(exactly = 1) { anyConstructed().check(any())}` – Akshay Hazari Dec 23 '21 at 05:35
  • // a complete example to mockk a Date constructor will be.; mockkConstructor(Date::class); every { anyConstructed().time } returns Date().time; – Akhha8 Jul 27 '22 at 17:58
  • It would be useful to add code which demonstrates the combined use of these two clauses. – Jameson Jul 20 '23 at 02:15
-2

MockK is a lib for unit testing your code. Don't use it for mocking constructor. You can use PowerMock for mocking constructor if you really need to mock constructor.

Vova
  • 956
  • 8
  • 22
  • 4
    For those that only want to unit test the class under test and not other classes, mocking constructors of objects your class under test uses is a perfectly fine way to use mocks. PowerMockito.whenNew works great with java, however PowerMockito currently doesn't work with Kotlin companion objects which is why I looked to Mockk as an alternative testing framework. – Scott Nov 15 '18 at 14:44