Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
643 views
in Technique[技术] by (71.8m points)

android - Mockito cannot mock this class?

I'm writing some unit tests for my app but i'm having the following error:

org.mockito.exceptions.base.MockitoException: 
Mockito cannot mock this class: class com.example.outsideintddexample.Engine.
Can not mock final classes with the following settings :
 - explicit serialization (e.g. withSettings().serializable())
 - extra interfaces (e.g. withSettings().extraInterfaces(...))

This is the class Engine:

package com.example.outsideintddexample

import android.util.Log
import kotlinx.coroutines.delay

class Engine(
    var temperature: Int = 15,
    var isTurnedOn: Boolean = false
) {

    suspend fun turnOn() {
        isTurnedOn = true
        delay(5000)
        Log.d("Teste", "Hello World")
        temperature = 95
    }
}

My test implementation:

class CarShould {

    private val engine: Engine = mock()
    private val car = Car(engine,5.0)


    @get:Rule
    var rule = MainCoroutineScopeRule()


    @Test
    fun looseFuelWhenItTurnsOn() = runBlockingTest {
        car.turnOn()

        assertEquals(4.5, car.fuel)
    }

    @Test
    fun turnOnItsEngine() = runBlockingTest {
        car.turnOn()

        verify(engine, times(1)).turnOn()
    }

I tried adding unitTests.returnDefaultValues = true into my gradle app but the error remains

I'm using testImplementation 'com.nhaarman.mockitokotlin2:mockito-kotlin:2.1.0' and testImplementation 'org.mockito:mockito-inline:2.21.0'

question from:https://stackoverflow.com/questions/65647528/mockito-cannot-mock-this-class

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...