Mockito无法模拟/监视的原因是:最终类。

huangapple go评论70阅读模式
英文:

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 &#39;org.mockito:mockito-inline:2.13.0&#39;

=> Currently I have

testImplementation &quot;org.mockito:mockito-inline:2.28.2&quot;

I also have this single line in my MockMaker file :

mock-maker-inline

Then you can see my following code :

object ApiHelper {

fun &lt;T&gt; createService(
        url: String,
        clazz: Class&lt;T&gt;
    ): 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.

huangapple
  • 本文由 发表于 2020年1月3日 18:43:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/59577137.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定