Skip to content

Commit 78e3ec1

Browse files
committed
add tests for the argThat(matcher: ArgumentMatcher<T>) function
1 parent bf17bc4 commit 78e3ec1

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
package test
2+
3+
import com.nhaarman.expect.expect
4+
import com.nhaarman.mockitokotlin2.argThat
5+
import com.nhaarman.mockitokotlin2.mock
6+
import com.nhaarman.mockitokotlin2.whenever
7+
import org.junit.Test
8+
import org.mockito.ArgumentMatcher
9+
import org.mockito.internal.matchers.VarargMatcher
10+
import org.mockito.invocation.InvocationOnMock
11+
import org.mockito.stubbing.Answer
12+
13+
/**
14+
*
15+
*/
16+
class VarArgMatcherTest : TestBase() {
17+
18+
@Test
19+
fun testVarargAnySuccess() {
20+
val t = mock<Tested>()
21+
22+
// a matcher to check if any of the varargs was equals to "b"
23+
val matcher = VarargAnyMatcher<String, Boolean>({ "b" == it }, true, false)
24+
25+
whenever(t.something(argThat(matcher))).thenAnswer(matcher)
26+
27+
assert(t.something("a", "b", "c"))
28+
}
29+
30+
@Test
31+
fun testVarargAnyFail() {
32+
val t = mock<Tested>()
33+
34+
// a matcher to check if any of the varargs was equals to "d"
35+
val matcher = VarargAnyMatcher<String, Boolean>({ "d" == it }, true, false)
36+
37+
whenever(t.something(argThat(matcher))).thenAnswer(matcher)
38+
39+
assert(!t.something("a", "b", "c"))
40+
}
41+
42+
/**
43+
* a test class with a vararg function to test
44+
*/
45+
interface Tested {
46+
fun something(vararg values: String): Boolean
47+
}
48+
49+
/**
50+
* a VarargMatcher implementation for varargs of type [T] that will answer with type [R] if any of the var args
51+
* matched. Needs to keep state between matching invocations.
52+
*/
53+
private class VarargAnyMatcher<T, R>(
54+
private val match: ((T) -> Boolean),
55+
private val success: R,
56+
private val failure: R
57+
) : ArgumentMatcher<T>, VarargMatcher, Answer<R> {
58+
private var anyMatched = false
59+
60+
override fun matches(t: T): Boolean {
61+
anyMatched = anyMatched or match(t)
62+
return true
63+
}
64+
65+
override fun answer(i: InvocationOnMock) = if (anyMatched) success else failure
66+
}
67+
68+
}

0 commit comments

Comments
 (0)