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:
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'
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.
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.
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()
Simply adding
testImplementation("org.mockito:mockito-inline:2.8.47")
resolved the issue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With