12

With mockk, to mock constructors, we can do something like (taken from documentation):

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) }

I'd like to check on the parameters of my constructor. Something like:

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

mockkConstructor(MockCls::class)

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

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

verify { anyConstructed<MockCls>(10).add(1, 2) } // success
verify { anyConstructed<MockCls>(5).add(1, 2) } // fail

I didn't find any way to check constructor parameters right now.

Happy
  • 1,815
  • 2
  • 18
  • 33

2 Answers2

1

This is now a feature in Mockk starting from 1.11.0.

mockkConstructor(MockCls::class)

// ...

verify { constructedWith<MockCls>(10).add(1, 2) } 
verify { constructedWith<MockCls>(5).add(1, 2)  }

See Mockk - Constructor mocks.

u-ways
  • 6,136
  • 5
  • 31
  • 47
  • Which seems to be introduced as a result of [your feature request](https://github.com/mockk/mockk/issues/209). – u-ways Feb 24 '23 at 23:49
0

Unfortunately, it is currently not possible, as shown in the feature request you kindly made.

Ellen Spertus
  • 6,576
  • 9
  • 50
  • 101