Use Spek and Mockito in Android Kotlin
Create an Android kotlin project.
Add dependencies to app/build.gradle
Implement an interface DataSource
.
Implement a class Arg
.
Replace content of test file ExampleUnitTest.kt
to
Run test, then you would got:
java.lang.IllegalStateException: any(Arg::class.java) must not be null
That’s because any() always return default value of given class, for primitive type, it’ll return primitive default value, for class, null will return.
Kotlin method does not accept null value if not declared nullable as arg: ClassName?
.
You can override any() function to solve this problem.
Add a utils file Extensions.kt
to test project.
Make some change to ExampleUnitTest.kt
From
Mockito.`when`(dataSource.fetch(anyInt(), any(Arg::class.java))).thenReturn(1)
to
Mockito.`when`(dataSource.fetch(anyInt(), any())).thenReturn(1)
Add import import com.jmengxy.kotlinspek.utils.any
Re-Run test, everything works fine.