Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add fun <T> MockKMatcherScope.any(KClass<T>): T #1005

Merged
merged 4 commits into from Jul 11, 2023

Conversation

ghackett
Copy link
Contributor

Premise

In transitioning from mockito to mockk, the one feature I've been missing is Mockito's defaultAnswer concept.

It seems like we can actually replicate this concept in mockk using reflection, however we're blocked w/o a way to define an any() matcher given a KClass or KType instead of a reified type.

The Change

This PR currently adds only the needed fun any(KClass) and fun match(Matcher, KClass) functions to the api to open up the possibility of mockking via reflection, and avoids trying to define new dsl for declaring default answers.

We also demonstrate two examples of reflective mockking. In both examples we mock a TestBuilder and tell it to always return itself. This is just to demonstrate the possibilities we'd be opening up with this change.

@ghackett ghackett marked this pull request as ready for review December 19, 2022 14:48
@nicchristeller
Copy link

I've been trying to do very similar, and came to the same conclusion.

fun <T> MockKMatcherScope.any(KClass<T>): T would be super useful.

@ghackett
Copy link
Contributor Author

👋 For the mockk maintainers, is this kind of change something that could be considered? If so, what does this PR need to become acceptable/mergable? I'm happy to put in the work, just need some guidance on what's missing.

@ghackett
Copy link
Contributor Author

In the meantime, I went ahead and shipped a library that enables this functionality today and does attempt to define a DSL for reflective mocking. Check it out at https://episode6.github.io/reflective-mockk/

@Raibaz
Copy link
Collaborator

Raibaz commented Jul 10, 2023

Ah, I completely missed on this, thanks @Kevinrob for reminding me 😊

@ghackett, would you please mind adding documentation for the new API methods you add in README.md?

After that I think this can be merged.

Thanks a lot for putting this together!

@ghackett ghackett force-pushed the feature/reflection-any-matcher branch from fbd7290 to 34743a7 Compare July 10, 2023 15:27
@ghackett
Copy link
Contributor Author

Awesome! Rebased and updated with a readme entry. Thanks @Raibaz!

@ghackett ghackett requested a review from Kevinrob July 10, 2023 15:29
@Raibaz Raibaz merged commit ca59598 into mockk:master Jul 11, 2023
26 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

4 participants