Mockito.spy and doReturn() does not work when using Kotlin by lazy
See original GitHub issueVersion 2.18.3
open class Target{
open val a:Int = 0
val b:Int by lazy {
10 + a
}
}
@RunWith(RobolectricTestRunner::class)
class MyTest {
@Test
fun test() {
val target = spy(Target())
whenever(target.a).doReturn(10)
assertEquals(20, target.b)
}
}
junit.framework.AssertionFailedError:
Expected :20
Actual :10
<Click to see difference>
Issue Analytics
- State:
- Created 5 years ago
- Comments:6
Top Results From Across the Web
Kotlin lazy block not executed when using Mockito and ...
If I construct MyComponent manually then the lazy block is executed - but this won't inject my mocks. How can I ensure the...
Read more >Kotlin + Mockito + NullPointerException thrown when stubbing ...
Coding example for the question Kotlin + Mockito + NullPointerException ... You should use the onBlocking method to properly mock the suspend function....
Read more >Kotlin with Mockito | Baeldung on Kotlin
In this short article, we'll see how we can mock using Mockito in Kotlin. If you want to learn more about the library,...
Read more >Kotlin Testability – Part 1 - Styling Android
The obvious solution to this is to mock these objects, but we cannot do that if the class under test actually creates these...
Read more >Android Unit Testing with Mockito - RayWenderlich.com
Before proceeding to create these tests, it's important to mention that Kotlin classes and methods by default are final. Mockito won't work with ......
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
You can’t mock spies like this. You are accessing
a
on the concrete class. The proper way to mock this is to do:This way, you are referencing the spy, and not the concrete class.
For this reason, I strongly suggest you stick with the
doReturn().when()
style syntax instead ofwhenever().doReturn()
style. The latter may work with mocks, but then if you ever switch to a spy, you will see failures even though your test code didn’t change.I can reproduce this as well. Any new information on this?