Convert Figma logo to code with AI

mockito logomockito-kotlin

Using Mockito with Kotlin

3,106
201
3,106
76

Top Related Projects

5,389

mocking library for Kotlin

Using Mockito with Kotlin

PowerMock is a Java framework that allows you to unit test code normally regarded as untestable.

6,314

✅ The 5th major version of the programmer-friendly testing framework for Java and the JVM

Android Unit Testing Framework

Quick Overview

Mockito-kotlin is a small library that provides helper functions to work with Mockito in Kotlin. It aims to provide a more idiomatic and concise way to use Mockito in Kotlin projects, leveraging Kotlin's language features to make mocking and testing more intuitive and less verbose.

Pros

  • Provides Kotlin-specific extensions and functions for Mockito, improving readability and reducing boilerplate
  • Leverages Kotlin's null-safety features, making it easier to work with nullable types in tests
  • Offers better integration with Kotlin's syntax, such as lambda expressions and infix functions
  • Maintains compatibility with Java Mockito, allowing for gradual adoption in existing projects

Cons

  • Adds an additional dependency to your project, which may increase complexity
  • Some developers may prefer using pure Mockito to maintain consistency across Java and Kotlin codebases
  • Learning curve for developers already familiar with Java Mockito, as some syntax and patterns differ
  • May lag behind the latest Mockito updates, depending on maintenance frequency

Code Examples

  1. Creating a mock:
val myMock = mock<MyClass>()
  1. Stubbing a method with any argument:
whenever(myMock.doSomething(any())).thenReturn("mocked result")
  1. Verifying method calls:
verify(myMock, times(2)).doSomething(argThat { it.startsWith("test") })
  1. Using Kotlin's infix functions for more readable assertions:
myMock should have called(myMock::doSomething).with(eq("test argument"))

Getting Started

To use mockito-kotlin in your Kotlin project, add the following dependency to your build file:

For Gradle (build.gradle.kts):

dependencies {
    testImplementation("org.mockito.kotlin:mockito-kotlin:4.1.0")
}

For Maven (pom.xml):

<dependency>
    <groupId>org.mockito.kotlin</groupId>
    <artifactId>mockito-kotlin</artifactId>
    <version>4.1.0</version>
    <scope>test</scope>
</dependency>

Then, in your test files, import the necessary functions:

import org.mockito.kotlin.*

You can now start using mockito-kotlin in your tests!

Competitor Comparisons

5,389

mocking library for Kotlin

Pros of MockK

  • More idiomatic Kotlin syntax and features
  • Supports coroutines and other Kotlin-specific constructs
  • Easier mocking of final classes and objects

Cons of MockK

  • Steeper learning curve for developers familiar with Mockito
  • Slightly more verbose syntax for simple mocking scenarios
  • Less widespread adoption compared to Mockito

Code Comparison

MockK:

val car = mockk<Car>()
every { car.drive(any()) } returns "Driving"
verify { car.drive(Direction.NORTH) }

Mockito-Kotlin:

val car = mock<Car>()
whenever(car.drive(any())).thenReturn("Driving")
verify(car).drive(Direction.NORTH)

MockK provides a more Kotlin-centric approach with its DSL, while Mockito-Kotlin maintains a syntax closer to Java-based Mockito. MockK's every and verify blocks offer a more fluent API, whereas Mockito-Kotlin uses separate function calls for stubbing and verification.

Both libraries serve the purpose of mocking in Kotlin, but MockK is designed specifically for Kotlin, offering better integration with language features. Mockito-Kotlin, being an adaptation of Mockito, may be more familiar to developers transitioning from Java but might not fully leverage Kotlin's capabilities.

Using Mockito with Kotlin

Pros of mockito-kotlin

  • More actively maintained with frequent updates
  • Better integration with Kotlin-specific features
  • Larger community and more extensive documentation

Cons of mockito-kotlin

  • Slightly steeper learning curve for Kotlin beginners
  • May have occasional compatibility issues with newer Kotlin versions

Code Comparison

mockito-kotlin:

val mock = mock<MyClass>()
whenever(mock.someMethod()).thenReturn("result")
verify(mock).someMethod()

mockito-kotlin:

val mock = mock(MyClass::class.java)
`when`(mock.someMethod()).thenReturn("result")
verify(mock).someMethod()

The main difference is that mockito-kotlin provides more idiomatic Kotlin syntax and type inference, while mockito-kotlin uses a more Java-like approach.

Both libraries offer similar functionality for mocking in Kotlin, but mockito-kotlin is generally preferred for Kotlin projects due to its better language integration and more active development. However, mockito-kotlin may be a suitable choice for teams transitioning from Java or working in mixed Java/Kotlin codebases.

PowerMock is a Java framework that allows you to unit test code normally regarded as untestable.

Pros of PowerMock

  • Can mock static methods, final classes, and private methods
  • Allows mocking of system classes and constructors
  • Provides more extensive mocking capabilities for legacy code

Cons of PowerMock

  • Requires more setup and configuration
  • Can lead to slower test execution due to bytecode manipulation
  • May encourage poor design practices by allowing mocking of non-injectable dependencies

Code Comparison

PowerMock:

@RunWith(PowerMockRunner.class)
@PrepareForTest(StaticClass.class)
public class TestClass {
    @Test
    public void testStaticMethod() {
        PowerMockito.mockStatic(StaticClass.class);
        when(StaticClass.staticMethod()).thenReturn("mocked");
    }
}

Mockito-Kotlin:

@Test
fun testMethod() {
    val mock = mock<MyClass>()
    whenever(mock.someMethod()).thenReturn("mocked")
}

PowerMock offers more extensive mocking capabilities, especially for legacy code and system classes. However, it requires more setup and can potentially lead to design issues. Mockito-Kotlin, on the other hand, provides a simpler and more Kotlin-friendly approach to mocking, but with some limitations compared to PowerMock's capabilities.

6,314

✅ The 5th major version of the programmer-friendly testing framework for Java and the JVM

Pros of JUnit5

  • Comprehensive testing framework with extensive features for Java
  • Supports parallel test execution for improved performance
  • Offers powerful parameterized tests and dynamic test generation

Cons of JUnit5

  • Steeper learning curve compared to Mockito-Kotlin
  • Requires more setup and configuration for advanced features
  • Less focused on mocking, which is Mockito-Kotlin's specialty

Code Comparison

JUnit5:

@ParameterizedTest
@ValueSource(strings = {"racecar", "radar", "able was I ere I saw elba"})
void palindromes(String candidate) {
    assertTrue(StringUtils.isPalindrome(candidate));
}

Mockito-Kotlin:

val mock = mock<List<String>> {
    on { get(0) } doReturn "first"
    on { get(1) } doReturn "second"
}
assertEquals("first", mock[0])
assertEquals("second", mock[1])

Summary

JUnit5 is a full-featured testing framework for Java, offering a wide range of capabilities including parameterized tests and parallel execution. Mockito-Kotlin, on the other hand, is specifically designed for mocking in Kotlin, providing a more streamlined and Kotlin-friendly approach to creating mock objects. While JUnit5 offers more comprehensive testing features, Mockito-Kotlin excels in its focused approach to mocking, making it easier to use for specific mocking scenarios in Kotlin projects.

Android Unit Testing Framework

Pros of Robolectric

  • Provides a complete Android testing environment without the need for an emulator or device
  • Allows testing of Android-specific components like Activities, Services, and ContentProviders
  • Faster test execution compared to instrumented tests on emulators or devices

Cons of Robolectric

  • Limited to unit testing and cannot fully replicate real device behavior
  • May not catch all UI-related issues or device-specific problems
  • Steeper learning curve due to its complex setup and configuration

Code Comparison

Robolectric (Android activity test):

@RunWith(RobolectricTestRunner::class)
class MyActivityTest {
    @Test
    fun clickingButton_shouldChangeText() {
        val activity = Robolectric.setupActivity(MyActivity::class.java)
        activity.findViewById<Button>(R.id.button).performClick()
        assertEquals("Clicked", activity.findViewById<TextView>(R.id.result).text)
    }
}

Mockito-Kotlin (Mocking a dependency):

@Test
fun testUserService() {
    val mockDao = mock<UserDao>()
    whenever(mockDao.getUser(1)).thenReturn(User(1, "John"))
    val userService = UserService(mockDao)
    assertEquals("John", userService.getUserName(1))
}

Robolectric focuses on Android-specific testing, while Mockito-Kotlin is a general-purpose mocking framework for Kotlin. Robolectric is better suited for testing Android components, while Mockito-Kotlin excels in isolating dependencies and unit testing non-Android-specific code.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Mockito-Kotlin

Download Nexus Snapshot

A small library that provides helper functions to work with Mockito in Kotlin.

Install

Mockito-Kotlin is available on Maven Central. For Gradle users, add the following to your build.gradle, replacing x.x.x with the latest version:

testImplementation "org.mockito.kotlin:mockito-kotlin:x.x.x"

Example

A test using Mockito-Kotlin typically looks like the following:

@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())
}

For more info and samples, see the Wiki.

Building

Mockito-Kotlin is built with Gradle.

  • ./gradlew build builds and tests the project
  • ./gradlew publishToMavenLocal installs the maven artifacts in your local repository
  • ./gradlew check runs the test suite (See Testing below)

Versioning

Mockito-Kotlin roughly follows SEMVER

Testing

Mockito-Kotlin's test suite is located in a separate tests module, to allow running the tests using several Kotlin versions whilst still keeping the base module at a recent version.

  • ./gradlew check runs the checks including tests.

Usually it is enough to test only using the default Kotlin versions; CI will test against multiple versions. If you want to test using a different Kotlin version locally, add the -PtestKotlinVersion=1.2.3 argument to the Gradle invocation while running the tests.

Acknowledgements

mockito-kotlin was created and developed by nhaarman@ after which the repository was integrated into the official Mockito GitHub organization. We would like to thank Niek for the original idea and extensive work plus support that went into mockito-kotlin.