Skip to content

Commit

Permalink
Add ArgumentCaptor.singleValue (#529)
Browse files Browse the repository at this point in the history
Co-authored-by: Björn Michael <bjoern.michael@optimax-energy.de>
  • Loading branch information
bjmi and bjoern-michael authored Sep 22, 2024
1 parent 94bf867 commit c4b4cc1
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,13 @@ class KArgumentCaptor<out T : Any?>(
val lastValue: T
get() = captor.lastValue

/**
* The *only* captured value of the argument,
* or throws an exception if no value or more than one value was captured.
*/
val singleValue: T
get() = captor.singleValue

val allValues: List<T>
get() = captor.allValues

Expand Down Expand Up @@ -223,3 +230,6 @@ val <T> ArgumentCaptor<T>.thirdValue: T

val <T> ArgumentCaptor<T>.lastValue: T
get() = allValues.last()

val <T> ArgumentCaptor<T>.singleValue: T
get() = allValues.single()
32 changes: 32 additions & 0 deletions tests/src/test/kotlin/test/ArgumentCaptorTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ package test
import com.nhaarman.expect.expect
import com.nhaarman.expect.expectErrorWithMessage
import org.junit.Test
import org.mockito.ArgumentCaptor
import org.mockito.ArgumentMatchers
import org.mockito.ArgumentMatchers.anyLong
import org.mockito.kotlin.*
import java.util.*

Expand Down Expand Up @@ -126,6 +129,35 @@ class ArgumentCaptorTest : TestBase() {
expect(captor.lastValue).toBeNull()
}

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

/* When */
date.time = 5L

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

@Test(expected = IllegalArgumentException::class)
fun argumentCaptor_singleValue_properlyFails() {
/* Given */
val date: Date = mock()
val captor = argumentCaptor<Long>()
doNothing().whenever(date).time = captor.capture()

/* When */
date.time = 5L
date.time = 7L

/* Then */
expect(captor.singleValue).toBe(5)
}

@Test
fun argumentCaptor_multipleValues() {
/* Given */
Expand Down

0 comments on commit c4b4cc1

Please sign in to comment.