Mockito-Kotlin Project Introduction
Mockito-Kotlin is a specialized library crafted to enhance the ease of using the robust Mockito framework in Kotlin applications. By offering a series of helper functions, it integrates seamlessly into Kotlin projects, allowing developers to write clear and effective unit tests without the usual hassle.
Installation
The library is readily accessible from Maven Central, making it straightforward to include in any project. Gradle users can easily integrate Mockito-Kotlin by adding a simple line to their build.gradle
file:
testImplementation "org.mockito.kotlin:mockito-kotlin:x.x.x"
Replace x.x.x
with the most recent version number, ensuring access to the latest features and updates.
Practical Example
To give a sense of Mockito-Kotlin's simplicity and utility, consider the following example of a unit test:
@Test
fun doAction_doesSomething(){
/* Given */
val mock = mock<MyClass> {
on { getText() } doReturn "text"
}
val classUnderTest = ClassUnderTest(mock)
/* When */
classUnderTest.doAction()
/* Then */
verify(mock).doSomething(any())
}
This example demonstrates how to mock a Kotlin class, specify behavior, and verify interactions succinctly. The use of mockito-kotlin
keeps the test clean, readable, and effective.
For additional information and examples, the project’s Wiki is a valuable resource.
Building and Testing
Mockito-Kotlin is constructed with Gradle, providing several convenient build function commands:
./gradlew build
compiles and tests the entire project../gradlew publishToMavenLocal
installs Maven artifacts locally../gradlew check
executes the test suite.
The test suite is distinctively organized in a separate tests
module. This allows the project to be tested against multiple Kotlin versions while maintaining a contemporary base module version. For users who wish to try different Kotlin versions, the command ./gradlew check
supports the addition of a specific Kotlin version using -PtestKotlinVersion=1.2.3
.
Acknowledgements
The initial creation and development of mockito-kotlin
was spearheaded by Niek Haarman. His pioneering efforts laid the groundwork for this integration with the official Mockito GitHub organization. The contributions and ongoing support from the community reflect in the project’s evolution, making it an invaluable tool for Kotlin developers worldwide.