Mockito mock Kotlin Object类方法报错解决方法主要是解决在Kotlin编写的程序中使用Mockito进行测试时,对一个Kotlin的Object类的方法进行Mock时报错的问题。以下是完整攻略:
问题描述
在Kotlin编写的程序中,有一个Object类,比如:
object MyObject {
fun doSomething(): String = "do something"
}
现在我们想要对该Object类的doSomething()方法进行Mock,代码如下:
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.InjectMocks
import org.mockito.Mock
import org.mockito.junit.MockitoJUnitRunner
@RunWith(MockitoJUnitRunner::class)
class MyObjectTest {
@InjectMocks
lateinit var myObject: MyObject
@Mock
lateinit var myMock: MyObject
@Test
fun testDoSomething() {
`when`(myMock.doSomething()).thenReturn("mock something")
assertEquals("mock something", myObject.doSomething())
}
}
此时可以发现,在使用Mockito进行测试时,报错了:
org.mockito.exceptions.base.MockitoException:
Cannot mock/spy class com.example.MyObject$Companion
Mockito cannot mock/spy following:
- final classes
- anonymous classes
- primitive types, final methods or classes
解决方法
解决方法主要是在Mockito的Mock语句中使用PowerMockito,步骤如下:
- 在build.gradle文件中添加以下依赖:
testImplementation 'org.powermock:powermock-module-junit4:2.0.9'
testImplementation 'org.powermock:powermock-api-mockito2:2.0.9'
- 在测试类中使用@RunWith()注解和@PrepareForTest()注解:
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.InjectMocks
import org.mockito.Mock
import org.mockito.junit.MockitoJUnitRunner
import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner
@RunWith(PowerMockRunner::class)
@PrepareForTest(MyObject::class)
class MyObjectTest {
@InjectMocks
lateinit var myObject: MyObject
@Mock
lateinit var myMock: MyObject
@Test
fun testDoSomething() {
PowerMockito.mockStatic(MyObject::class.java)
`when`(MyObject.doSomething()).thenReturn("mock something")
assertEquals("mock something", myObject.doSomething())
}
}
此时,再次运行测试即可通过。
注意事项
- 在测试类中使用@RunWith(PowerMockRunner::class)注解,而不是@RunWith(MockitoJUnitRunner::class)注解;
- 在测试类中使用@PrepareForTest(MyObject::class)注解,参数是需要Mock的Kotlin Object类名;
- 在Mockito的Mock语句中使用PowerMockito,例如:PowerMockito.mockStatic(MyObject::class.java);
- 在Mockito的Mock语句中使用Kotlin Object名来进行Mock,例如:
when
(MyObject.doSomething()).thenReturn("mock something")。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Mockito mock Kotlin Object类方法报错解决方法 - Python技术站