Mockito.verify没有看到方法执行,即使它是

时间:2019-08-07 05:48:56

标签: android mockito rx-java2 powermock

我的错误: Error I have 错误代码:

@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"

Kinda解决方法

  1. powermock模拟的某些字段在“验证”时失败,但是用嘲笑模拟的字段不是;
  2. 如果没有mock-maker-inline,Mockito不能模拟未打开的字段,但是Mockito与Powermock模拟制造商内联冲突;
  3. Powermock可以将模拟制造商内联的调用委托给其他模拟制造商内联(https://github.com/powermock/powermock/wiki/PowerMock-Configuration
  4. 在失败的字段上使用Mockito.mock而不是@ Mock / Powermock模拟注入

使用PowerMockRunner进行“绿色”马铃薯测试方法的示例

    @Test
    fun potato() {
        potatoConsumer = mock() // <-
        Observable.just(Potato()).subscribe(potatoConsumer)
        verify(potatoConsumer).accept(potato)
    }

2 个答案:

答案 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对象时不断创建新实例,以免比较失败。