Skip to content

Commit a12e11f

Browse files
panelplnhaarman
authored andcommitted
Added argument captor overloads
1 parent fe1ddec commit a12e11f

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

mockito-kotlin/src/main/kotlin/com/nhaarman/mockitokotlin2/ArgumentCaptor.kt

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,13 +36,27 @@ inline fun <reified T : Any> argumentCaptor(): KArgumentCaptor<T> {
3636
return KArgumentCaptor(ArgumentCaptor.forClass(T::class.java), T::class)
3737
}
3838

39+
/**
40+
* Creates a [KArgumentCaptor] for given type, taking in a lambda to allow fast verification.
41+
*/
42+
inline fun <reified T : Any> argumentCaptor(f: KArgumentCaptor<T>.() -> Unit): KArgumentCaptor<T> {
43+
return argumentCaptor<T>().apply(f)
44+
}
45+
3946
/**
4047
* Creates a [KArgumentCaptor] for given nullable type.
4148
*/
4249
inline fun <reified T : Any> nullableArgumentCaptor(): KArgumentCaptor<T?> {
4350
return KArgumentCaptor(ArgumentCaptor.forClass(T::class.java), T::class)
4451
}
4552

53+
/**
54+
* Creates a [KArgumentCaptor] for given nullable type, taking in a lambda to allow fast verification.
55+
*/
56+
inline fun <reified T : Any> nullableArgumentCaptor(f: KArgumentCaptor<T?>.() -> Unit): KArgumentCaptor<T?> {
57+
return nullableArgumentCaptor<T>().apply(f)
58+
}
59+
4660
/**
4761
* Alias for [ArgumentCaptor.capture].
4862
*/

tests/src/test/kotlin/test/ArgumentCaptorTest.kt

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package test
22

33
import com.nhaarman.expect.expect
4+
import com.nhaarman.expect.expectErrorWithMessage
45
import com.nhaarman.mockitokotlin2.*
56
import org.junit.Test
67
import java.util.*
@@ -117,4 +118,36 @@ class ArgumentCaptorTest : TestBase() {
117118
expect(secondValue).toBe(2)
118119
}
119120
}
121+
122+
@Test
123+
fun argumentCaptor_withSingleValue_lambda() {
124+
/* Given */
125+
val date: Date = mock()
126+
127+
/* When */
128+
date.time = 5L
129+
130+
/* Then */
131+
argumentCaptor<Long> {
132+
verify(date).time = capture()
133+
expect(lastValue).toBe(5L)
134+
}
135+
}
136+
137+
@Test
138+
fun argumentCaptor_withSingleValue_lambda_properlyFails() {
139+
/* Given */
140+
val date: Date = mock()
141+
142+
/* When */
143+
date.time = 5L
144+
145+
/* Then */
146+
expectErrorWithMessage("Expected: 3 but was: 5") on {
147+
argumentCaptor<Long> {
148+
verify(date).time = capture()
149+
expect(lastValue).toBe(3L)
150+
}
151+
}
152+
}
120153
}

0 commit comments

Comments
 (0)