Skip to content

Commit c4b4cc1

Browse files
bjmibjoern-michael
andauthored
Add ArgumentCaptor.singleValue (#529)
Co-authored-by: Björn Michael
1 parent 94bf867 commit c4b4cc1

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

mockito-kotlin/src/main/kotlin/org/mockito/kotlin/ArgumentCaptor.kt

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -190,6 +190,13 @@ class KArgumentCaptor(
190190
val lastValue: T
191191
get() = captor.lastValue
192192

193+
/**
194+
* The *only* captured value of the argument,
195+
* or throws an exception if no value or more than one value was captured.
196+
*/
197+
val singleValue: T
198+
get() = captor.singleValue
199+
193200
val allValues: List<T>
194201
get() = captor.allValues
195202

@@ -223,3 +230,6 @@ val ArgumentCaptor.thirdValue: T
223230

224231
val <T> ArgumentCaptor<T>.lastValue: T
225232
get() = allValues.last()
233+
234+
val <T> ArgumentCaptor<T>.singleValue: T
235+
get() = allValues.single()

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

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,9 @@ package test
33
import com.nhaarman.expect.expect
44
import com.nhaarman.expect.expectErrorWithMessage
55
import org.junit.Test
6+
import org.mockito.ArgumentCaptor
7+
import org.mockito.ArgumentMatchers
8+
import org.mockito.ArgumentMatchers.anyLong
69
import org.mockito.kotlin.*
710
import java.util.*
811

@@ -126,6 +129,35 @@ class ArgumentCaptorTest : TestBase() {
126129
expect(captor.lastValue).toBeNull()
127130
}
128131

132+
@Test
133+
fun argumentCaptor_singleValue() {
134+
/* Given */
135+
val date: Date = mock()
136+
137+
/* When */
138+
date.time = 5L
139+
140+
/* Then */
141+
val captor = argumentCaptor<Long>()
142+
verify(date).time = captor.capture()
143+
expect(captor.singleValue).toBe(5L)
144+
}
145+
146+
@Test(expected = IllegalArgumentException::class)
147+
fun argumentCaptor_singleValue_properlyFails() {
148+
/* Given */
149+
val date: Date = mock()
150+
val captor = argumentCaptor<Long>()
151+
doNothing().whenever(date).time = captor.capture()
152+
153+
/* When */
154+
date.time = 5L
155+
date.time = 7L
156+
157+
/* Then */
158+
expect(captor.singleValue).toBe(5)
159+
}
160+
129161
@Test
130162
fun argumentCaptor_multipleValues() {
131163
/* Given */

0 commit comments

Comments
 (0)