Mocking extension function in Kotlin

后端 未结 4 1427
暗喜
暗喜 2021-02-19 01:19

How to mock Kotlin extension function using Mockito or PowerMock in tests? Since they are resolved statically should they be tested as static method calls or as non static?

4条回答
  •  粉色の甜心
    2021-02-19 01:38

    Instance extension functions can be stubbed and verified like this with the help of mockito-kotlin:

    data class Bar(thing: Int)
    
    class Foo {
       fun Bar.bla(anotherThing: Int): Int { ... }
    }
    
    val bar = Bar(thing = 1)
    val foo = mock()
    
    with(foo) {
      whenever(any().bla(any()).doReturn(3)
    }
    
    verify(foo).apply {
      bar.bla(anotherThing = 2)
    }
    

提交回复
热议问题