From cbb0aa7b551b1db343ba05ee54755774a6ad9eb3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B6rn=20Michael?= Date: Sun, 22 Sep 2024 05:26:47 +0200 Subject: [PATCH] Add ArgumentCaptor.singleValue --- .../org/mockito/kotlin/ArgumentCaptor.kt | 10 ++++++ .../test/kotlin/test/ArgumentCaptorTest.kt | 32 +++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/mockito-kotlin/src/main/kotlin/org/mockito/kotlin/ArgumentCaptor.kt b/mockito-kotlin/src/main/kotlin/org/mockito/kotlin/ArgumentCaptor.kt index 4b9017c9..d10a650b 100644 --- a/mockito-kotlin/src/main/kotlin/org/mockito/kotlin/ArgumentCaptor.kt +++ b/mockito-kotlin/src/main/kotlin/org/mockito/kotlin/ArgumentCaptor.kt @@ -190,6 +190,13 @@ class KArgumentCaptor( 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 get() = captor.allValues @@ -223,3 +230,6 @@ val ArgumentCaptor.thirdValue: T val ArgumentCaptor.lastValue: T get() = allValues.last() + +val ArgumentCaptor.singleValue: T + get() = allValues.single() diff --git a/tests/src/test/kotlin/test/ArgumentCaptorTest.kt b/tests/src/test/kotlin/test/ArgumentCaptorTest.kt index 79c901a6..323d7a45 100644 --- a/tests/src/test/kotlin/test/ArgumentCaptorTest.kt +++ b/tests/src/test/kotlin/test/ArgumentCaptorTest.kt @@ -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.* @@ -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() + 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() + doNothing().whenever(date).time = captor.capture() + + /* When */ + date.time = 5L + date.time = 7L + + /* Then */ + expect(captor.singleValue).toBe(5) + } + @Test fun argumentCaptor_multipleValues() { /* Given */