alibaba / testable-mock

换种思路写Mock,让单元测试更简单
https://alibaba.github.io/testable-mock/
MIT License
1.83k stars 310 forks source link

Mock Kotlin的 companion object 方法异常 #312

Open LitterSun opened 1 year ago

LitterSun commented 1 year ago

OneUtil.kt

class OneUtil {
    fun add(x: Int, y: Int): Int {
        return staticAdd(x, y)
    }

    companion object {
        fun staticAdd(x: Int, y: Int): Int {
            return x + y
        }
    }
}

OneUtilTest.kt

class OneUtilTest {
    class Mock {
        @MockInvoke(targetClass = OneUtil::class)
        private fun staticAdd(x: Int, y: Int): Int {
            return 100
        }
    }

    @Test
    fun exampleTest() {
        assertEquals(100, OneUtil().add(1, 3))
    }
}

执行后出错

Bad type on operand stack
Exception Details:
  Location:
    com/example/xxx/OneUtil.add(II)I @8: invokevirtual
  Reason:
    Type 'com/example/xxx/OneUtil$Companion' (current frame, stack[2]) is not assignable to integer
  Current Frame:
    bci: @8
    flags: { }
    locals: { 'com/example/xxx/OneUtil', integer, integer }
    stack: { 'com/example/xxx/OneUtilTest$Mock', null, 'com/example/xxx/OneUtil$Companion', integer }
  Bytecode:
    0000000: b800 2601 b200 281b b600 2cac          

java.lang.VerifyError: Bad type on operand stack
Exception Details:
  Location:
    com/example/xxx/OneUtil.add(II)I @8: invokevirtual
  Reason:
    Type 'com/example/xxx/OneUtil$Companion' (current frame, stack[2]) is not assignable to integer
  Current Frame:
    bci: @8
    flags: { }
    locals: { 'com/example/xxx/OneUtil', integer, integer }
    stack: { 'com/example/xxx/OneUtilTest$Mock', null, 'com/example/xxx/OneUtil$Companion', integer }
  Bytecode:
    0000000: b800 2601 b200 281b b600 2cac