@@ -4,6 +4,10 @@ import com.nhaarman.expect.expect
44import com.nhaarman.expect.expectErrorWithMessage
55import com.nhaarman.mockitokotlin2.*
66import org.junit.Test
7+ import org.mockito.ArgumentMatcher
8+ import org.mockito.internal.matchers.VarargMatcher
9+ import org.mockito.invocation.InvocationOnMock
10+ import org.mockito.stubbing.Answer
711import java.io.IOException
812
913class MatchersTest : TestBase () {
@@ -195,4 +199,51 @@ class MatchersTest : TestBase() {
195199 verify(this ).nullableString(same(null ))
196200 }
197201 }
202+
203+ @Test
204+ fun testVarargAnySuccess () {
205+ /* Given */
206+ val t = mock<Methods >()
207+ // a matcher to check if any of the varargs was equals to "b"
208+ val matcher = VarargAnyMatcher <String , Boolean >({ " b" == it }, true , false )
209+
210+ /* When */
211+ whenever(t.varargBooleanResult(argThat(matcher))).thenAnswer(matcher)
212+
213+ /* Then */
214+ expect(t.varargBooleanResult(" a" , " b" , " c" )).toBe(true )
215+ }
216+
217+ @Test
218+ fun testVarargAnyFail () {
219+ /* Given */
220+ val t = mock<Methods >()
221+ // a matcher to check if any of the varargs was equals to "d"
222+ val matcher = VarargAnyMatcher <String , Boolean >({ " d" == it }, true , false )
223+
224+ /* When */
225+ whenever(t.varargBooleanResult(argThat(matcher))).thenAnswer(matcher)
226+
227+ /* Then */
228+ expect(t.varargBooleanResult(" a" , " b" , " c" )).toBe(false )
229+ }
230+
231+ /* *
232+ * a VarargMatcher implementation for varargs of type [T] that will answer with type [R] if any of the var args
233+ * matched. Needs to keep state between matching invocations.
234+ */
235+ private class VarargAnyMatcher <T , R >(
236+ private val match : ((T ) -> Boolean ),
237+ private val success : R ,
238+ private val failure : R
239+ ) : ArgumentMatcher<T>, VarargMatcher, Answer<R> {
240+ private var anyMatched = false
241+
242+ override fun matches (t : T ): Boolean {
243+ anyMatched = anyMatched or match(t)
244+ return true
245+ }
246+
247+ override fun answer (i : InvocationOnMock ) = if (anyMatched) success else failure
248+ }
198249}
0 commit comments