@RunWith(PowerMockRunner::class)
@PrepareForTest(PotatoProvider::class, PotatoConsumer::class)
class WantedButNotInvoked {
@Mock
lateinit var potatoConsumer: PotatoConsumer
@Test
fun potato() {
Observable.just(Potato()).subscribe(potatoConsumer)
verify(potatoConsumer).accept(Potato())
//verify(potatoConsumer).accept(any()) //-> This fails too with the same reason
}
}
data class Potato(val value: Int = 1)
class PotatoConsumer : Consumer<Potato> {
override fun accept(t: Potato?) {
println(t)
}
}
所以我订阅了这个模拟(potatoConsumer),rxJava调用了“ accept”,并把它标记为交互,但是模拟认为这不是我所期望的,为什么?
图书馆的版本使用了她:
mockitoVersion = '2.8.9'
mockitoAndroidVersion = '2.7.22'
powerMockVersion="2.0.2"
kotlinMockito="2.1.0"
rxKotlin = "2.3.0"
rxJavaVersion = "2.2.10"
mock-maker-inline
,Mockito不能模拟未打开的字段,但是Mockito与Powermock模拟制造商内联冲突; 使用PowerMockRunner进行“绿色”马铃薯测试方法的示例
@Test
fun potato() {
potatoConsumer = mock() // <-
Observable.just(Potato()).subscribe(potatoConsumer)
verify(potatoConsumer).accept(potato)
}
答案 0 :(得分:1)
我对PowerMock
不熟悉,但是我尝试了此测试,测试通过了:
@Test
fun potato() {
fakePotatoProvider = Mockito.mock(PotatoProvider::class.java)
potatoConsumer = Mockito.mock(PotatoConsumer::class.java)
`when`(fakePotatoProvider.getObservable()).thenReturn(Observable.just(Potato()))
fakePotatoProvider.getObservable().subscribe(potatoConsumer)
verify(potatoConsumer).accept(Potato())
}
答案 1 :(得分:0)
可能是因为您没有传递相同的Potato()
实例。尝试将您的代码重构为此
@Test
fun potato() {
val testPotato = Potato()
`when`(fakePotatoProvider.getObservable()).thenReturn(Observable.just(testPotato))
fakePotatoProvider.getObservable().subscribe(potatoConsumer)
verify(potatoConsumer).accept(testPotato)
}
如上所述,可能失败的原因是在传递Potato
对象时不断创建新实例,以免比较失败。