Closed ToffeeLu closed 3 years ago
@Test fun testBWasCalledByA() = runBlocking{ val a = mock<A>{ onBlocking { b() } doReturn 3 } val res = a.a() println(res) }
@ToffeeLu As for the example you've provided you invoke an unstubbed function on your mock (this line: val res = a.a()
) .
Maybe try:
open class A{
open suspend fun a():Int{
return b()
}
open suspend fun b(): Int{
return 2
}
}
class HelloTest {
@Test
fun testBWasCalledByA() = runBlocking{
val a = mock<A>{
onBlocking { b() } doReturn 3
}
val res = a.b() // invoke the stubbed function instead
println(res)
}
}
I've also added open
declarations to your class under test (class A
). Not needed if you use inline-mockmaker, AllOpen-plugin or similar.
@bohsen Thanks for the reply along with the open
thing.
But how can I verify b()
is called by a()
? That's what I want to verify by UT. If I also mock a()
, then it's meaningless.
@bohsen I just figured out myself. Add this line helps doCallRealMethod().whenever(a).a()
.
I'm wondering is it possible to enrich the wiki? It's quite simple now. Otherwise people need to read Mockito document entirely, and then find APIs here.
@Test
fun testBWasCalledByA() = runBlocking{
val a = mock<A>{
onBlocking { b() } doReturn 3
}
doCallRealMethod().whenever(a).a()
val res = a.a()
println(res)
}
@ToffeeLu Sorry for not reading the code/issue thoroughly. Good to hear you found the solution anyway.
Regarding the wiki, PR's are welcome I believe.
Thanks @bohsen , close for now. Will send PR later for the WIKI.
Below code should print 3, but actually it throws below error. Even after I remove all suspend, the print value is 0 instead of 3. It can be reproduced locally even I copy this test to this repo, https://github.com/mockito/mockito-kotlin/blob/main/mockito-kotlin/src/test/kotlin/test/CoroutinesTest.kt