alibaba / alibaba/testable-mock

Mock Kotlin的 companion object 方法异常

Open
#312 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
Java
Stars
1.8k
Forks
306
PR merge metrics
No merged PRs in 30d

Description

OneUtil.kt
```kotlin
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
```kotlin
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
```

Contributor guide

No contributing guide indexed for this repository

Research direction

Start with the OneUtil.kt and OneUtilTest.kt reproducer, run exampleTest, and inspect the reported VerifyError and bytecode for the companion-object call. Done means the test runs successfully and assertEquals(100, OneUtil().add(1, 3)) passes without a stack-verification error.

Written by the indexing model from the issue text.

Assessment

Tech stack
kotlin
Domain
testing
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.