Skip to content

Tweak stubbing idiom to allow for more kotlin regular expression #47

@Groostav

Description

@Groostav

Hello,

I've been independently working on getting kotlin working with Mockito, and have done very little work in comparison to your work.

One thing I have got that I think your repo could use however is an idiom around setting up stubbed and mocked methods:

val fileTracker = mock<LastModifiedTimeTracker> {
    on { fileWasModified() }.thenReturn(true)
}

this is implemented with the relatively simple extension methods:

inline fun <reified T : Any> mock(stubbing: KStubbing<T>.() -> Unit) : T
        = Mockito.mock(T::class.java).apply { stubbing.invoke(KStubbing(this)) }

class KStubbing<TMock>(private val mock: TMock) {
    fun <TMethodReturn> on(methodCall: TMethodReturn) = Mockito.`when`(methodCall)
    fun <TMethodReturn> on(methodCall: TMock.() -> TMethodReturn) = Mockito.`when`(mock.methodCall());
}

i have not done extensive testing, but in thinking about it, the call order that mockito needs so badly should be preserved.

  1. on the first line, a mock is created.
  2. using that mock as a return value, the apply method is called
  3. stubbing.invoke is effectively when(methodCall)
  4. the specifics of both the on methods will have the arguments executed first, meaning aMock.call() will happen before Mockito.when, as is expected.

another win here is that unit is a type that is a subtype of Object, so no more doAnswer(...).when nonsense :)

I can put this into a pull request and add some tests if you like.

Happy mocking!

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions