Skip to content

Commit

Permalink
Merge pull request #254 from nhaarman/igorwojda-1.x
Browse files Browse the repository at this point in the history
Simplified argument captor API (originally #242)
  • Loading branch information
nhaarman authored May 10, 2018
2 parents fe1ddec + a12e11f commit bbbcef9
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -36,13 +36,27 @@ inline fun <reified T : Any> argumentCaptor(): KArgumentCaptor<T> {
return KArgumentCaptor(ArgumentCaptor.forClass(T::class.java), T::class)
}

/**
* Creates a [KArgumentCaptor] for given type, taking in a lambda to allow fast verification.
*/
inline fun <reified T : Any> argumentCaptor(f: KArgumentCaptor<T>.() -> Unit): KArgumentCaptor<T> {
return argumentCaptor<T>().apply(f)
}

/**
* Creates a [KArgumentCaptor] for given nullable type.
*/
inline fun <reified T : Any> nullableArgumentCaptor(): KArgumentCaptor<T?> {
return KArgumentCaptor(ArgumentCaptor.forClass(T::class.java), T::class)
}

/**
* Creates a [KArgumentCaptor] for given nullable type, taking in a lambda to allow fast verification.
*/
inline fun <reified T : Any> nullableArgumentCaptor(f: KArgumentCaptor<T?>.() -> Unit): KArgumentCaptor<T?> {
return nullableArgumentCaptor<T>().apply(f)
}

/**
* Alias for [ArgumentCaptor.capture].
*/
Expand Down
33 changes: 33 additions & 0 deletions tests/src/test/kotlin/test/ArgumentCaptorTest.kt
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package test

import com.nhaarman.expect.expect
import com.nhaarman.expect.expectErrorWithMessage
import com.nhaarman.mockitokotlin2.*
import org.junit.Test
import java.util.*
Expand Down Expand Up @@ -117,4 +118,36 @@ class ArgumentCaptorTest : TestBase() {
expect(secondValue).toBe(2)
}
}

@Test
fun argumentCaptor_withSingleValue_lambda() {
/* Given */
val date: Date = mock()

/* When */
date.time = 5L

/* Then */
argumentCaptor<Long> {
verify(date).time = capture()
expect(lastValue).toBe(5L)
}
}

@Test
fun argumentCaptor_withSingleValue_lambda_properlyFails() {
/* Given */
val date: Date = mock()

/* When */
date.time = 5L

/* Then */
expectErrorWithMessage("Expected: 3 but was: 5") on {
argumentCaptor<Long> {
verify(date).time = capture()
expect(lastValue).toBe(3L)
}
}
}
}

0 comments on commit bbbcef9

Please sign in to comment.