what do you guys use for mocking in kotlin? I've ...
# getting-started
what do you guys use for mocking in kotlin? I've been using mockito since forever... but with kotling i've run into issues with suspending functions
Copy code
   .then {
this simple thing I can't do because
doesn't give me a coroutine context. Do you use Mockk? Some other libraries? What are the pros and cons? Bonus question: is there some best practice to test when you have final classes? (which are the default in kotlin).
I consider myself expert in kotlin by now, but I'm just starting using coroutines (used RxJava before) and i've been encountering new issues 😉 should have I asked this in #coroutines ?
Mockito doesn’t understand Kotlin, so it won’t be able to work with coroutines. Mockk has native support for mocking suspending functions (
coEvery { }
and running suspending code as an answer to a mocked function (
coAnswers { }
), and it works very well in my experience. To my knowledge, it is the only kotlin-specific option for mocking. The API is very similar to Mockito, and it’s very easy to migrate from one to the other. You can run both Mockito and Mockk in the same test suite so you can just write your new tests in Mockk without having to rewrite your old tests. I don’t know if you can use both libraries in the same test, though, so I’d suggest for each test class you just use one or the other.
Thanks, do you have any article / doc link to suggest for the migration from mockito to mockk?
Nothing in particular, just reading the documentation (https://mockk.io/, everything’s on one page). Things are named very similar to Mockito, and just looking at the examples should be enough to get started if you’re comfortable with Mockito
Tomorrow I'll try it thanks
This article will help you stubbing coroutines with Mockk: https://blog.joshua-greenwood.com/testing-coroutines-is-easy-with-mockk/ Generally you should prefer it to Mockito, which has limitations for Kotlin (but is great for Java), like Casey said. If you still want to use Mockito, you can add this lib: https://github.com/nhaarman/mockito-kotlin/wiki which provides some additional functions to ease usage from Kotlin but it won’t solve this problem.
👍 1
Bonus answer: the problem with classes being final by default is solved by Mockk, which can mock all your classes without problem. On another side Spring, for example, had to come up with a compiler plugin that opens all your K classes, otherwise it wouldn’t be able to wrap them with its proxies
I'm curious, how does it do it under the hood?
I’m not completely sure but I think it manipulates the bytecode at compile-time to make a class
, so it’s final when you compile and you have all the expected checks but effectively non-final at runtime. not completely sure but it manipulates bytecode at compile-time, making the class