# Mockito-Kotlin

[![Maven Central](https://img.shields.io/maven-central/v/org.mockito.kotlin/mockito-kotlin.svg?label=Maven%20Central align="left")](https://search.maven.org/search?q=g:%22org.mockito.kotlin%22%20AND%20a:%22mockito-kotlin%22)

[Mockito-Kotlin](https://github.com/mockito/mockito-kotlin) is a small library that provides helper functions to work with [Mockito](https://github.com/mockito/mockito) in Kotlin. It is a great choice for Java devs already familiar with Mockito. Mockito is a widely used Java testing framework that helps create mock objects for unit testing. It allows developers to isolate code from dependencies, define behaviors, and verify method calls.

# Creating Mocks

🤮 Legacy Java Mockito syntax. Don't do it.

```kotlin
val mock = mock(MyDependency::class.java)
```

😍 Now, don't these look better?

```kotlin
val mock: MyDependency = mock()
```

```kotlin
val mock = mock<MyDependency>
```

😍 Creating mocks inline can be quite handy!

```kotlin
val subject = MyClass(mock())
```

# Stubbing

🤮 Mockito stubbing method `when` requires backticks since `when` is a reserved keyword in Kotlin.

```kotlin
`when`(mock.foo()).doReturn(null)
```

🙂 Mockito-Kotlin adds a `whenever` alias so you don't have to type or look at those ugly backticks.

```kotlin
whenever(mock.foo()).doReturn(null)
```

😍 Even better, Mockito-Kotlin adds a new stubbing DSL! It can be used when creating a new mock and on existing mocks.

```kotlin
val mock: MyDependency = mock {
    on { foo() } doReturn { "default" }
    on { bar() } doReturn { 1 }
}

@Test
fun test() {
    mock.stub {
        on { foo() } doReturn { "override" }
    }
}
```

😍 It even supports stubbing of suspend functions (Kotlin Coroutines).

```kotlin
mock {
    onBlocking { apiCall() } doReturn "Hello World"
}
```
