英文:
Mockito cannot mock/spy because : Final Class
问题
我知道这个问题被问了很多次,但我按照很多答案尝试了,但仍然没有成功。
在这个链接中,他们说我们需要在gradle中添加以下依赖:
testImplementation 'org.mockito:mockito-inline:2.13.0'
但是,我当前使用的是:
testImplementation "org.mockito:mockito-inline:2.28.2"
另外,我在我的MockMaker文件中也有这一行:
mock-maker-inline
然后你可以看到我的以下代码:
object ApiHelper {
fun <T> createService(
url: String,
clazz: Class<T>
): T
}
在我的UITEST中:
@Mock
private lateinit var service: myService
private lateinit var apiHelper: ApiHelper
@Before
fun setUp() {
apiHelper = mock(ApiHelper::class.java)
given(ApiHelper.createService(
anyString(),
MyService::class.java,
)).willReturn(service)
}
我的代码有什么问题吗?我漏掉了什么吗?
英文:
I know this question is asked a lot of time, but I followed a lot of answer and it still didnt work
https://stackoverflow.com/questions/14292863/how-to-mock-a-final-class-with-mockito
in this link, they said that we have to add in our gradle :
testImplementation 'org.mockito:mockito-inline:2.13.0'
=> Currently I have
testImplementation "org.mockito:mockito-inline:2.28.2"
I also have this single line in my MockMaker file :
mock-maker-inline
Then you can see my following code :
object ApiHelper {
fun <T> createService(
url: String,
clazz: Class<T>
): T
}
in my UITEST
@Mock
private lateinit var service: myService
private lateinit var apiHelper: ApiHelper
@Before
fun setUp() {
apiHelper = mock(ApiHelper::class.java)
given(ApiHelper.createService(
anyString(),
MyService::class.java,
)).willReturn(service)
}
What is wrong with my code? Did I missed something?
答案1
得分: 5
Kotlin的模拟库 http://mockk.io
我以前也使用过mockito,但在编写时遇到了很多问题。
相反,mockk功能强大,使得编写测试更容易,并且对象模拟正适合您的情况。
英文:
> mocking library for Kotlin http://mockk.io
I also used mockito before, it has so many problems when writing.
Instead, the mockk is powerful and it makes your testing easier to write and
object mocks is just for your case
答案2
得分: 3
这种模拟最终类的方法不幸地不能用于UI测试。对于您的UI测试,您将不得不使用kotlin allopen插件。
英文:
This approach for mocking final classes unfortunately doesn't work for UI tests.
For your UI tests, you'll have to work with the kotlin allopen plugin.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论