Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't mock final class in test using Mockito with Kotlin

I'm trying to run a simple instrumentation test:

class DefaultTest {

    private val networkHelper = Mockito.mock(NetworkHelperImpl::class.java)

    @Test fun inter() {
        given(networkHelper.isConnectedToNetwork()).willReturn(true)
        assertFalse { networkHelper.isConnectedToNetwork(false) }
    }
}

But i cant bacause of error:

Mockito cannot mock/spy because :
- final class

How can i avoid it?

As this guide says:

https://antonioleiva.com/mockito-2-kotlin/

I'm create file:

enter image description here

With this line:

mock-maker-inline

But nothing changes.

Gradle is bad(i'm learning), but it must work. I use unit test too, so now i have:

//Tests
testImplementation 'junit:junit:4.13-beta-3'

testImplementation 'org.jetbrains.kotlin:kotlin-stdlib:1.3.41'
testImplementation 'org.jetbrains.kotlin:kotlin-test-junit:1.3.41'

androidTestImplementation 'org.mockito:mockito-core:3.0.0'
androidTestImplementation 'org.mockito:mockito-android:2.24.5'
androidTestImplementation "com.nhaarman.mockitokotlin2:mockito-kotlin:2.1.0"

testImplementation 'org.amshove.kluent:kluent:1.14'

androidTestImplementation 'androidx.test:runner:1.2.0'
androidTestImplementation 'androidx.test:core:1.2.0'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test:rules:1.2.0'
like image 488
KirstenLy Avatar asked Aug 17 '19 12:08

KirstenLy


People also ask

Can Mockito mock a final class?

Configure Mockito for Final Methods and Classes Mockito checks the extensions directory for configuration files when it is loaded. This file enables the mocking of final methods and classes.

Does Mockito work with Kotlin?

Mockito has been around since the early days of Android development and eventually became the de-facto mocking library for writing unit tests. Mockito and Mockk are written in Java and Kotlin, respectively, and since Kotlin and Java are interoperable, they can exist within the same project.

What is SPYK in Kotlin?

Spy allows mocking only a particular part of some class. By using annotation, we can declare a variable like below example @Spyk private lateinit var object: MyClass. And by using spyk method. val object = spyk()


1 Answers

Simply adding

testImplementation("org.mockito:mockito-inline:2.8.47")

resolved the issue.

like image 119
Janani Sampath Kumar Avatar answered Oct 23 '22 12:10

Janani Sampath Kumar