commit | e1de1f64d2ad4d280a4ec7afe020fddab4128999 | [log] [tgz] |
---|---|---|
author | Micah Zoltu <micah@zoltu.net> | Thu Jul 21 15:43:18 2016 +0000 |
committer | GitHub <noreply@github.com> | Thu Jul 21 15:43:18 2016 +0000 |
tree | abc4ff27f40b1f974ebdd8267c9b3a48d77429c0 | |
parent | bb4ac76a66c61033565ab9a792fd4a255a77161c [diff] |
Makes `mock` return non-null types. Since `Mockito.mock` is a Java function it returns a Kotlin platform type. By adding an explicit return type to the wrapper, the kotlin version of `mock` will now return a non-platform type. In this case, we know that `Mockito.mock` doesn't return null so we can safely make the wrapper return a non-null type. We add the `!!` to make it clear to the reader our intent is to strip the platform type at this point, and also make the Kotlin compiler add an explicit null-check "just in case" before returning from the kotlin `mock` method.
A small library that provides helper functions to work with Mockito in Kotlin.
Mockito-Kotlin is available on JCenter. For Gradle users, add the following to your build.gradle
:
repositories { jcenter() } dependencies { testCompile "com.nhaarman:mockito-kotlin:x.x.x" }
Due to Kotlin‘s reified type parameters, if the type can be inferred, you don’t have to specify it explicitly:
Java:
MyClass c = mock(Myclass.class); c.doSomething(mock(MyOtherClass.class));
Kotlin:
val c : MyClass = mock() c.doSomething(mock())
If the type can't be inferred, you can pass it like so:
val d = mock<MyClass>()
Mockito‘s any(Class<T>)
often returns null
for non-primitive classes. In Kotlin, this can be a problem due to its null-safety feature. This library creates non-null instances when necessary. Again, if the type can be inferred, you don’t have to specify it explicitely:
Java:
verify(myClass).doSomething(any(String.class));
Kotlin:
verify(myClass).doSomething(any()); // Non-nullable parameter type is inferred
For generic arrays, use the anyArray()
method:
verify(myClass).setItems(anyArray())
There are some cases where Mockito-Kotlin cannot create an instance of a class. This can for instance be when a constructor has some specific preconditions for its parameters. You can register instance creators
to overcome this:
MockitoKotlin.registerInstanceCreator<MyClass> { MyClass(5) }
Whenever MockitoKotlin needs to create an instance of MyClass
, this function is called, giving you ultimate control over how these instances are created.
These instance creators work on a per-file basis: for each of your test files you will need to register them again.
Using higher-order functions, you can write very clear expectations about expected values. For example:
Kotlin:
verify(myClass).setItems(argThat{ size == 2 })
Most of Mockito‘s static functions are available as top-level functions. That means, IDE’s like IntelliJ can easily import and autocomplete them, saving you the hassle of manually importing them.