Mocking Extension functions
See original GitHub issueIs it possible to stub Kotlin extension methods?
Let’s say I have an extension function:
fun Context.findColor(color: Int) = resources.getColor(color)
And I have a mock of an Context
I would like to stub:
val mock = mock<Context>()
whenever(mock.findColor(color)).thenReturn(color)
Right now it doesn’t work. Is there a way to achieve this?
Issue Analytics
- State:
- Created 6 years ago
- Reactions:10
- Comments:13
Top Results From Across the Web
Mocking extension function in Kotlin - Stack Overflow
I think MockK can help you. It supports mocking extension functions too. You can use it to mock object-wide extensions:
Read more >Mock top-level and extension functions | MockK Guidebook
Depending on where an extension function is located, it may correspond to a top-level function or a class member. If placed inside a...
Read more >Mockk- Testing Extension Functions | by Byte Sized Bits
Extension functions are one of the many amazing things Kotlin provides us. Extension functions can be useful to extend an existing library ...
Read more >Mockito and Extension Functions in Kotlin - Kenan Sevindik
Being able to define extension functions to classes that belong to third-party libraries looks very nice at the first point.
Read more >Mock Extension Methods - Mocking Features | Telerik JustMock
Extension methods are a special kind of static methods that are called as if they were instance methods on the extended type. Mocking...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
If you have instance extension functions (which are basically syntactic sugar), you can easily use mockito-kotlin for them:
I guess the ‘official’ answer would be “don’t mock extension functions”. They’re basically static functions, which Mockito does not support. Create a proper abstraction for them, or resort to tools like PowerMock or MocK.