diff options
Diffstat (limited to 'tests/src/test')
-rw-r--r-- | tests/src/test/kotlin/test/ArgumentCaptorTest.kt | 229 | ||||
-rw-r--r-- | tests/src/test/kotlin/test/BDDMockitoTest.kt | 131 | ||||
-rw-r--r-- | tests/src/test/kotlin/test/Classes.kt | 108 | ||||
-rw-r--r-- | tests/src/test/kotlin/test/EqTest.kt | 101 | ||||
-rw-r--r-- | tests/src/test/kotlin/test/MatchersTest.kt | 334 | ||||
-rw-r--r-- | tests/src/test/kotlin/test/MockMaker.kt | 10 | ||||
-rw-r--r-- | tests/src/test/kotlin/test/MockingTest.kt | 357 | ||||
-rw-r--r-- | tests/src/test/kotlin/test/OngoingStubbingTest.kt | 340 | ||||
-rw-r--r-- | tests/src/test/kotlin/test/SpyTest.kt | 141 | ||||
-rw-r--r-- | tests/src/test/kotlin/test/StubberTest.kt | 103 | ||||
-rw-r--r-- | tests/src/test/kotlin/test/TestBase.kt | 11 | ||||
-rw-r--r-- | tests/src/test/kotlin/test/VerificationTest.kt | 115 | ||||
-rw-r--r-- | tests/src/test/kotlin/test/VerifyTest.kt | 96 | ||||
-rw-r--r-- | tests/src/test/kotlin/test/createinstance/NullCasterTest.kt | 31 | ||||
-rw-r--r-- | tests/src/test/kotlin/test/inline/UsingMockMakerInlineTest.kt | 116 |
15 files changed, 2223 insertions, 0 deletions
diff --git a/tests/src/test/kotlin/test/ArgumentCaptorTest.kt b/tests/src/test/kotlin/test/ArgumentCaptorTest.kt new file mode 100644 index 0000000..703e750 --- /dev/null +++ b/tests/src/test/kotlin/test/ArgumentCaptorTest.kt @@ -0,0 +1,229 @@ +package test + +import com.nhaarman.expect.expect +import com.nhaarman.expect.expectErrorWithMessage +import org.junit.Test +import org.mockito.kotlin.* +import java.util.* + +class ArgumentCaptorTest : TestBase() { + + @Test + fun argumentCaptor_withSingleValue() { + /* Given */ + val date: Date = mock() + + /* When */ + date.time = 5L + + /* Then */ + val captor = argumentCaptor<Long>() + verify(date).time = captor.capture() + expect(captor.lastValue).toBe(5L) + } + + @Test + fun argumentCaptor_destructuring2() { + /* Given */ + val date: Date = mock() + + /* When */ + date.time = 5L + + /* Then */ + val (captor1, captor2) = argumentCaptor<Long, Long>() + verify(date).time = captor1.capture() + verify(date).time = captor2.capture() + expect(captor1.lastValue).toBe(5L) + expect(captor2.lastValue).toBe(5L) + } + + @Test + fun argumentCaptor_destructuring3() { + /* Given */ + val date: Date = mock() + + /* When */ + date.time = 5L + + /* Then */ + val (captor1, captor2, captor3) = argumentCaptor<Long, Long, Long>() + val verifyCaptor: KArgumentCaptor<Long>.() -> Unit = { + verify(date).time = capture() + expect(lastValue).toBe(5L) + } + captor1.apply(verifyCaptor) + captor2.apply(verifyCaptor) + captor3.apply(verifyCaptor) + } + + @Test + fun argumentCaptor_destructuring4() { + /* Given */ + val date: Date = mock() + + /* When */ + date.time = 5L + + /* Then */ + val (captor1, captor2, captor3, captor4) = argumentCaptor<Long, Long, Long, Long>() + val verifyCaptor: KArgumentCaptor<Long>.() -> Unit = { + verify(date).time = capture() + expect(lastValue).toBe(5L) + } + captor1.apply(verifyCaptor) + captor2.apply(verifyCaptor) + captor3.apply(verifyCaptor) + captor4.apply(verifyCaptor) + } + + @Test + fun argumentCaptor_destructuring5() { + /* Given */ + val date: Date = mock() + + /* When */ + date.time = 5L + + /* Then */ + val (captor1, captor2, captor3, captor4, captor5) = argumentCaptor<Long, Long, Long, Long, Long>() + val verifyCaptor: KArgumentCaptor<Long>.() -> Unit = { + verify(date).time = capture() + expect(lastValue).toBe(5L) + } + captor1.apply(verifyCaptor) + captor2.apply(verifyCaptor) + captor3.apply(verifyCaptor) + captor4.apply(verifyCaptor) + captor5.apply(verifyCaptor) + } + + @Test + fun argumentCaptor_withNullValue_usingNonNullable() { + /* Given */ + val m: Methods = mock() + + /* When */ + m.nullableString(null) + + /* Then */ + val captor = argumentCaptor<String>() + verify(m).nullableString(captor.capture()) + expect(captor.lastValue).toBeNull() + } + + @Test + fun argumentCaptor_withNullValue_usingNullable() { + /* Given */ + val m: Methods = mock() + + /* When */ + m.nullableString(null) + + /* Then */ + val captor = nullableArgumentCaptor<String>() + verify(m).nullableString(captor.capture()) + expect(captor.lastValue).toBeNull() + } + + @Test + fun argumentCaptor_multipleValues() { + /* Given */ + val date: Date = mock() + + /* When */ + date.time = 5L + date.time = 7L + + /* Then */ + val captor = argumentCaptor<Long>() + verify(date, times(2)).time = captor.capture() + expect(captor.allValues).toBe(listOf(5, 7)) + } + + @Test + fun argumentCaptor_multipleValuesIncludingNull() { + /* Given */ + val m: Methods = mock() + + /* When */ + m.nullableString("test") + m.nullableString(null) + + /* Then */ + val captor = nullableArgumentCaptor<String>() + verify(m, times(2)).nullableString(captor.capture()) + expect(captor.allValues).toBe(listOf("test", null)) + } + + @Test + fun argumentCaptor_callProperties() { + /* Given */ + val m: Methods = mock() + + /* When */ + m.int(1) + m.int(2) + m.int(3) + m.int(4) + m.int(5) + + /* Then */ + argumentCaptor<Int>().apply { + verify(m, times(5)).int(capture()) + + expect(firstValue).toBe(1) + expect(secondValue).toBe(2) + expect(thirdValue).toBe(3) + expect(lastValue).toBe(5) + } + } + + @Test(expected = IndexOutOfBoundsException::class) + fun argumentCaptor_callPropertyNotAvailable() { + /* Given */ + val m: Methods = mock() + + /* When */ + m.int(1) + + /* Then */ + argumentCaptor<Int>().apply { + verify(m).int(capture()) + + expect(secondValue).toBe(2) + } + } + + @Test + fun argumentCaptor_withSingleValue_lambda() { + /* Given */ + val date: Date = mock() + + /* When */ + date.time = 5L + + /* Then */ + argumentCaptor<Long> { + verify(date).time = capture() + expect(lastValue).toBe(5L) + } + } + + @Test + fun argumentCaptor_withSingleValue_lambda_properlyFails() { + /* Given */ + val date: Date = mock() + + /* When */ + date.time = 5L + + /* Then */ + expectErrorWithMessage("Expected: 3 but was: 5") on { + argumentCaptor<Long> { + verify(date).time = capture() + expect(lastValue).toBe(3L) + } + } + } +} diff --git a/tests/src/test/kotlin/test/BDDMockitoTest.kt b/tests/src/test/kotlin/test/BDDMockitoTest.kt new file mode 100644 index 0000000..0472163 --- /dev/null +++ b/tests/src/test/kotlin/test/BDDMockitoTest.kt @@ -0,0 +1,131 @@ +package test + +import com.nhaarman.expect.expect +import org.junit.Test +import org.mockito.kotlin.* +import org.mockito.stubbing.Answer + +class BDDMockitoTest { + + @Test + fun given_will_properlyStubs() { + /* Given */ + val mock = mock<Methods>() + + /* When */ + given(mock.stringResult()) will Answer<String> { "Test" } + + /* Then */ + expect(mock.stringResult()).toBe("Test") + } + + @Test + fun given_willReturn_properlyStubs() { + /* Given */ + val mock = mock<Methods>() + + /* When */ + given(mock.stringResult()).willReturn("Test") + + /* Then */ + expect(mock.stringResult()).toBe("Test") + } + + @Test + fun givenLambda_willReturn_properlyStubs() { + /* Given */ + val mock = mock<Methods>() + + /* When */ + given { mock.stringResult() }.willReturn("Test") + + /* Then */ + expect(mock.stringResult()).toBe("Test") + } + + @Test + fun given_willReturnLambda_properlyStubs() { + /* Given */ + val mock = mock<Methods>() + + /* When */ + given(mock.stringResult()).willReturn { "Test" } + + /* Then */ + expect(mock.stringResult()).toBe("Test") + } + + @Test + fun givenLambda_willReturnLambda_properlyStubs() { + /* Given */ + val mock = mock<Methods>() + + /* When */ + given { mock.stringResult() } willReturn { "Test" } + + /* Then */ + expect(mock.stringResult()).toBe("Test") + } + + @Test + fun given_willAnswer_properlyStubs() { + /* Given */ + val mock = mock<Methods>() + + /* When */ + given(mock.stringResult()).willAnswer { "Test" } + + /* Then */ + expect(mock.stringResult()).toBe("Test") + } + + @Test + fun given_willAnswerInfix_properlyStubs() { + /* Given */ + val mock = mock<Methods>() + + /* When */ + given(mock.stringResult()) willAnswer { "Test" } + + /* Then */ + expect(mock.stringResult()).toBe("Test") + } + + @Test + fun given_willAnswerInfix_withInvocationInfo_properlyStubs() { + /* Given */ + val mock = mock<Methods>() + + /* When */ + given(mock.stringResult(any())) willAnswer { invocation -> + (invocation.arguments[0] as String) + .reversed() + } + + /* Then */ + expect(mock.stringResult("Test")).toBe("tseT") + } + + @Test(expected = IllegalStateException::class) + fun given_willThrowInfix_properlyStubs() { + /* Given */ + val mock = mock<Methods>() + + /* When */ + given(mock.stringResult()) willThrow { IllegalStateException() } + mock.stringResult() + } + + @Test + fun then() { + /* Given */ + val mock = mock<Methods>() + whenever(mock.stringResult()).thenReturn("Test") + + /* When */ + mock.stringResult() + + /* Then */ + org.mockito.kotlin.then(mock).should().stringResult() + } +} diff --git a/tests/src/test/kotlin/test/Classes.kt b/tests/src/test/kotlin/test/Classes.kt new file mode 100644 index 0000000..87b758d --- /dev/null +++ b/tests/src/test/kotlin/test/Classes.kt @@ -0,0 +1,108 @@ +package test + +/* +* The MIT License +* +* Copyright (c) 2016 Niek Haarman +* Copyright (c) 2007 Mockito contributors +* +* Permission is hereby granted, free of charge, to any person obtaining a copy +* of this software and associated documentation files (the "Software"), to deal +* in the Software without restriction, including without limitation the rights +* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +* copies of the Software, and to permit persons to whom the Software is +* furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in +* all copies or substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +* THE SOFTWARE. +*/ + +open class Open { + open fun go(vararg arg: Any?) { + } + + open fun modifiesContents(a: IntArray) { + for (i in 0..a.size - 1) { + a[i] = a[i] + 1 + } + } + + open fun stringResult() = "Default" + + fun throwsNPE(): Any = throw NullPointerException("Test") +} + +class Closed + +interface Methods { + + fun intArray(i: IntArray) + fun closed(c: Closed) + fun closedArray(a: Array<Closed>) + fun closedNullableArray(a: Array<Closed?>) + fun closedCollection(c: Collection<Closed>) + fun closedList(c: List<Closed>) + fun closedStringMap(m: Map<Closed, String>) + fun closedSet(s: Set<Closed>) + fun string(s: String) + fun boolean(b: Boolean) + fun byte(b: Byte) + fun char(c: Char) + fun short(s: Short) + fun int(i: Int) + fun long(l: Long) + fun float(f: Float) + fun double(d: Double) + fun closedVararg(vararg c: Closed) + fun throwableClass(t: ThrowableClass) + fun nullableString(s: String?) + + fun stringResult(): String + fun stringResult(s: String): String + fun nullableStringResult(): String? + fun builderMethod(): Methods + fun varargBooleanResult(vararg values: String): Boolean + + fun nonDefaultReturnType(): ExtraInterface +} + +interface ExtraInterface + +abstract class ThrowingConstructor { + + constructor() { + error("Error in constructor") + } +} + +abstract class ThrowingConstructorWithArgument { + + constructor(s: String) { + error("Error in constructor: $s") + } +} + +abstract class NonThrowingConstructorWithArgument { + + constructor() { + error("Error in constructor") + } + + @Suppress("UNUSED_PARAMETER") + constructor(s: String) +} + +interface GenericMethods<T> { + fun genericMethod(): T + fun nullableReturnType(): T? +} + +class ThrowableClass(cause: Throwable) : Throwable(cause) diff --git a/tests/src/test/kotlin/test/EqTest.kt b/tests/src/test/kotlin/test/EqTest.kt new file mode 100644 index 0000000..2f64c09 --- /dev/null +++ b/tests/src/test/kotlin/test/EqTest.kt @@ -0,0 +1,101 @@ +package test + +/* + * The MIT License + * + * Copyright (c) 2016 Niek Haarman + * Copyright (c) 2007 Mockito contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +import com.nhaarman.expect.expect +import org.mockito.kotlin.eq +import org.mockito.kotlin.mock +import org.junit.After +import org.junit.Before +import org.junit.Test +import org.mockito.Mockito + +class EqTest : TestBase() { + + private val interfaceInstance: MyInterface = MyClass() + private val openClassInstance: MyClass = MyClass() + private val closedClassInstance: ClosedClass = ClosedClass() + + private lateinit var doAnswer: Open + + @Before + fun setup() { + /* Create a proper Mockito state */ + doAnswer = Mockito.doAnswer { }.`when`(mock()) + } + + @After + override fun tearDown() { + super.tearDown() + + /* Close `any` Mockito state */ + doAnswer.go(0) + } + + @Test + fun eqInterfaceInstance() { + /* When */ + val result = eq(interfaceInstance) + + /* Then */ + expect(result).toNotBeNull() + } + + @Test + fun eqOpenClassInstance() { + /* When */ + val result = eq(openClassInstance) + + /* Then */ + expect(result).toNotBeNull() + } + + @Test + fun eqClosedClassInstance() { + /* When */ + val result = eq(closedClassInstance) + + /* Then */ + expect(result).toNotBeNull() + } + + @Test + fun nullArgument() { + /* Given */ + val s: String? = null + + /* When */ + val result = eq(s) + + /* Then */ + expect(result).toBeNull() + } + + private interface MyInterface + private open class MyClass : MyInterface + class ClosedClass +} + diff --git a/tests/src/test/kotlin/test/MatchersTest.kt b/tests/src/test/kotlin/test/MatchersTest.kt new file mode 100644 index 0000000..afed69f --- /dev/null +++ b/tests/src/test/kotlin/test/MatchersTest.kt @@ -0,0 +1,334 @@ +package test + +import com.nhaarman.expect.expect +import com.nhaarman.expect.expectErrorWithMessage +import org.junit.Test +import org.mockito.ArgumentMatcher +import org.mockito.internal.matchers.VarargMatcher +import org.mockito.invocation.InvocationOnMock +import org.mockito.kotlin.* +import org.mockito.stubbing.Answer +import java.io.IOException +import kotlin.check + +class MatchersTest : TestBase() { + + @Test + fun anyString() { + mock<Methods>().apply { + string("") + verify(this).string(any()) + } + } + + @Test + fun anyInt() { + mock<Methods>().apply { + int(3) + verify(this).int(any()) + } + } + + @Test + fun anyClosedClass() { + mock<Methods>().apply { + closed(Closed()) + verify(this).closed(any()) + } + } + + @Test + fun anyIntArray() { + mock<Methods>().apply { + intArray(intArrayOf()) + verify(this).intArray(any()) + } + } + + @Test + fun anyClassArray() { + mock<Methods>().apply { + closedArray(arrayOf(Closed())) + verify(this).closedArray(anyArray()) + } + } + + @Test + fun anyNullableClassArray() { + mock<Methods>().apply { + closedNullableArray(arrayOf(Closed(), null)) + verify(this).closedNullableArray(anyArray()) + } + } + + @Test + fun anyStringVararg() { + mock<Methods>().apply { + closedVararg(Closed(), Closed()) + verify(this).closedVararg(anyVararg()) + } + } + + @Test + fun anyNull_neverVerifiesAny() { + mock<Methods>().apply { + nullableString(null) + verify(this, never()).nullableString(any()) + } + } + + @Test + fun anyNull_verifiesAnyOrNull() { + mock<Methods>().apply { + nullableString(null) + verify(this).nullableString(anyOrNull()) + } + } + + @Test + fun anyNull_forPrimitiveBoolean() { + mock<Methods>().apply { + boolean(false) + verify(this).boolean(anyOrNull()) + } + } + @Test + fun anyNull_forPrimitiveByte() { + mock<Methods>().apply { + byte(3) + verify(this).byte(anyOrNull()) + } + } + + @Test + fun anyNull_forPrimitiveChar() { + mock<Methods>().apply { + char('a') + verify(this).char(anyOrNull()) + } + } + + @Test + fun anyNull_forPrimitiveShort() { + mock<Methods>().apply { + short(3) + verify(this).short(anyOrNull()) + } + } + + @Test + fun anyNull_forPrimitiveInt() { + mock<Methods>().apply { + int(3) + verify(this).int(anyOrNull()) + } + } + + @Test + fun anyNull_forPrimitiveLong() { + mock<Methods>().apply { + long(3) + verify(this).long(anyOrNull()) + } + } + + @Test + fun anyNull_forPrimitiveFloat() { + mock<Methods>().apply { + float(3f) + verify(this).float(anyOrNull()) + } + } + + @Test + fun anyNull_forPrimitiveDouble() { + mock<Methods>().apply { + double(3.0) + verify(this).double(anyOrNull()) + } + } + + /** https://github.com/nhaarman/mockito-kotlin/issues/27 */ + @Test + fun anyThrowableWithSingleThrowableConstructor() { + mock<Methods>().apply { + throwableClass(ThrowableClass(IOException())) + verify(this).throwableClass(any()) + } + } + + @Test + fun listArgThat() { + mock<Methods>().apply { + closedList(listOf(Closed(), Closed())) + verify(this).closedList( + argThat { + size == 2 + } + ) + } + } + + @Test + fun listArgForWhich() { + mock<Methods>().apply { + closedList(listOf(Closed(), Closed())) + verify(this).closedList( + argForWhich { + size == 2 + } + ) + } + } + + @Test + fun listArgWhere() { + mock<Methods>().apply { + closedList(listOf(Closed(), Closed())) + verify(this).closedList( + argWhere { + it.size == 2 + } + ) + } + } + + @Test + fun listArgCheck() { + mock<Methods>().apply { + closedList(listOf(Closed(), Closed())) + verify(this).closedList( + check { + expect(it.size).toBe(2) + } + ) + } + } + + @Test + fun checkProperlyFails() { + mock<Methods>().apply { + closedList(listOf(Closed(), Closed())) + + expectErrorWithMessage("Argument(s) are different!") on { + verify(this).closedList( + check { + expect(it.size).toBe(1) + } + ) + } + } + } + + @Test + fun checkWithNullArgument_throwsError() { + mock<Methods>().apply { + nullableString(null) + + expectErrorWithMessage("null").on { + verify(this).nullableString(check {}) + } + } + } + + + @Test + fun isA_withNonNullableString() { + mock<Methods>().apply { + string("") + verify(this).string(isA<String>()) + } + } + + @Test + fun isA_withNullableString() { + mock<Methods>().apply { + nullableString("") + verify(this).nullableString(isA<String>()) + } + } + + @Test + fun same_withNonNullArgument() { + mock<Methods>().apply { + string("") + verify(this).string(same("")) + } + } + + @Test + fun same_withNullableNonNullArgument() { + mock<Methods>().apply { + nullableString("") + verify(this).nullableString(same("")) + } + } + + @Test + fun same_withNullArgument() { + mock<Methods>().apply { + nullableString(null) + verify(this).nullableString(same(null)) + } + } + + @Test + fun testVarargAnySuccess() { + /* Given */ + val t = mock<Methods>() + // a matcher to check if any of the varargs was equals to "b" + val matcher = VarargAnyMatcher<String, Boolean>({ "b" == it }, true, false) + + /* When */ + whenever(t.varargBooleanResult(argThat(matcher))).thenAnswer(matcher) + + /* Then */ + expect(t.varargBooleanResult("a", "b", "c")).toBe(true) + } + + @Test + fun testVarargAnyFail() { + /* Given */ + val t = mock<Methods>() + // a matcher to check if any of the varargs was equals to "d" + val matcher = VarargAnyMatcher<String, Boolean>({ "d" == it }, true, false) + + /* When */ + whenever(t.varargBooleanResult(argThat(matcher))).thenAnswer(matcher) + + /* Then */ + expect(t.varargBooleanResult("a", "b", "c")).toBe(false) + } + + /** https://github.com/nhaarman/mockito-kotlin/issues/328 */ + @Test + fun testRefEqForNonNullableParameter() { + mock<Methods>().apply { + /* When */ + val array = intArrayOf(2, 3) + intArray(array) + + /* Then */ + verify(this).intArray(refEq(array)) + } + } + + /** + * a VarargMatcher implementation for varargs of type [T] that will answer with type [R] if any of the var args + * matched. Needs to keep state between matching invocations. + */ + private class VarargAnyMatcher<T, R>( + private val match: ((T) -> Boolean), + private val success: R, + private val failure: R + ) : ArgumentMatcher<T>, VarargMatcher, Answer<R> { + private var anyMatched = false + + override fun matches(t: T): Boolean { + anyMatched = anyMatched or match(t) + return true + } + + override fun answer(i: InvocationOnMock) = if (anyMatched) success else failure + } +}
\ No newline at end of file diff --git a/tests/src/test/kotlin/test/MockMaker.kt b/tests/src/test/kotlin/test/MockMaker.kt new file mode 100644 index 0000000..54f3d91 --- /dev/null +++ b/tests/src/test/kotlin/test/MockMaker.kt @@ -0,0 +1,10 @@ +package test + +import org.mockito.internal.configuration.plugins.Plugins +import org.mockito.internal.creation.bytebuddy.InlineByteBuddyMockMaker + + +internal var mockMakerInlineEnabled: Boolean? = null +internal fun mockMakerInlineEnabled(): Boolean { + return mockMakerInlineEnabled ?: (Plugins.getMockMaker() is InlineByteBuddyMockMaker) +} diff --git a/tests/src/test/kotlin/test/MockingTest.kt b/tests/src/test/kotlin/test/MockingTest.kt new file mode 100644 index 0000000..43e6413 --- /dev/null +++ b/tests/src/test/kotlin/test/MockingTest.kt @@ -0,0 +1,357 @@ +package test + +import com.nhaarman.expect.expect +import com.nhaarman.expect.expectErrorWithMessage +import com.nhaarman.expect.fail +import org.mockito.kotlin.UseConstructor.Companion.parameterless +import org.mockito.kotlin.UseConstructor.Companion.withArguments +import org.mockito.kotlin.doReturn +import org.mockito.kotlin.mock +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever +import org.junit.Test +import org.mockito.Mockito +import org.mockito.exceptions.verification.WantedButNotInvoked +import org.mockito.listeners.InvocationListener +import org.mockito.mock.SerializableMode.BASIC +import java.io.PrintStream +import java.io.Serializable +import java.util.* + +class MockingTest : TestBase() { + + private lateinit var propertyInterfaceVariable: MyInterface + private lateinit var propertyClassVariable: MyClass + + @Test + fun localInterfaceValue() { + /* When */ + val instance: MyInterface = mock() + + /* Then */ + expect(instance).toNotBeNull() + } + + @Test + fun propertyInterfaceVariable() { + /* When */ + propertyInterfaceVariable = mock() + + /* Then */ + expect(propertyInterfaceVariable).toNotBeNull() + } + + @Test + fun localClassValue() { + /* When */ + val instance: MyClass = mock() + + /* Then */ + expect(instance).toNotBeNull() + } + + @Test + fun propertyClassVariable() { + /* When */ + propertyClassVariable = mock() + + /* Then */ + expect(propertyClassVariable).toNotBeNull() + } + + @Test + fun untypedVariable() { + /* When */ + val instance = mock<MyClass>() + + expect(instance).toNotBeNull() + } + + @Test + fun deepStubs() { + val cal: Calendar = mock(defaultAnswer = Mockito.RETURNS_DEEP_STUBS) + whenever(cal.time.time).thenReturn(123L) + expect(cal.time.time).toBe(123L) + } + + + @Test + fun testMockStubbing_lambda() { + /* Given */ + val mock = mock<Open>() { + on { stringResult() } doReturn "A" + } + + /* When */ + val result = mock.stringResult() + + /* Then */ + expect(result).toBe("A") + } + + @Test + fun testMockStubbing_normalOverridesLambda() { + /* Given */ + val mock = mock<Open>() { + on { stringResult() }.doReturn("A") + } + whenever(mock.stringResult()).thenReturn("B") + + /* When */ + val result = mock.stringResult() + + /* Then */ + expect(result).toBe("B") + } + + + @Test + fun mock_withCustomDefaultAnswer_parameterName() { + /* Given */ + val mock = mock<Methods>(defaultAnswer = Mockito.RETURNS_SELF) + + /* When */ + val result = mock.builderMethod() + + /* Then */ + expect(result).toBe(mock) + } + + @Test + fun mock_withSettingsAPI_extraInterfaces() { + /* Given */ + val mock = mock<Methods>( + extraInterfaces = arrayOf(ExtraInterface::class) + ) + + /* Then */ + expect(mock).toBeInstanceOf<ExtraInterface>() + } + + @Test + fun mock_withSettingsAPI_name() { + /* Given */ + val mock = mock<Methods>(name = "myName") + + /* When */ + expectErrorWithMessage("myName.stringResult()") on { + verify(mock).stringResult() + } + } + + @Test + fun mock_withSettingsAPI_defaultAnswer() { + /* Given */ + val mock = mock<Methods>(defaultAnswer = Mockito.RETURNS_MOCKS) + + /* When */ + val result = mock.nonDefaultReturnType() + + /* Then */ + expect(result).toNotBeNull() + } + + @Test + fun mock_withSettingsAPI_serializable() { + /* Given */ + val mock = mock<Methods>(serializable = true) + + /* Then */ + expect(mock).toBeInstanceOf<Serializable>() + } + + @Test + fun mock_withSettingsAPI_serializableMode() { + /* Given */ + val mock = mock<Methods>(serializableMode = BASIC) + + /* Then */ + expect(mock).toBeInstanceOf<Serializable>() + } + + @Test + fun mock_withSettingsAPI_verboseLogging() { + /* Given */ + val out = mock<PrintStream>() + System.setOut(out) + val mock = mock<Methods>(verboseLogging = true) + + try { + /* When */ + verify(mock).stringResult() + fail("Expected an exception") + } catch (e: WantedButNotInvoked) { + /* Then */ + verify(out).println("methods.stringResult();") + } + } + + @Test + fun mock_withSettingsAPI_invocationListeners() { + /* Given */ + var bool = false + val mock = mock<Methods>(invocationListeners = arrayOf(InvocationListener { bool = true })) + + /* When */ + mock.stringResult() + + /* Then */ + expect(bool).toHold() + } + + @Test + fun mock_withSettingsAPI_stubOnly() { + /* Given */ + val mock = mock<Methods>(stubOnly = true) + + /* Expect */ + expectErrorWithMessage("is a stubOnly() mock") on { + + /* When */ + verify(mock).stringResult() + } + } + + @Test + fun mock_withSettingsAPI_useConstructor() { + /* Given */ + expectErrorWithMessage("Unable to create mock instance of type ") on { + mock<ThrowingConstructor>(useConstructor = parameterless()) {} + } + } + + @Test + fun mock_withSettingsAPI_useConstructorWithArguments_failing() { + /* Given */ + expectErrorWithMessage("Unable to create mock instance of type ") on { + mock<ThrowingConstructorWithArgument>(useConstructor = withArguments("Test")) {} + } + } + + @Test + fun mock_withSettingsAPI_useConstructorWithArguments() { + /* When */ + val result = mock<NonThrowingConstructorWithArgument>(useConstructor = withArguments("Test")) {} + + /* Then */ + expect(result).toNotBeNull() + } + + @Test + fun mockStubbing_withSettingsAPI_extraInterfaces() { + /* Given */ + val mock = mock<Methods>(extraInterfaces = arrayOf(ExtraInterface::class)) {} + + /* Then */ + expect(mock).toBeInstanceOf<ExtraInterface>() + } + + @Test + fun mockStubbing_withSettingsAPI_name() { + /* Given */ + val mock = mock<Methods>(name = "myName") {} + + /* When */ + expectErrorWithMessage("myName.stringResult()") on { + verify(mock).stringResult() + } + } + + @Test + fun mockStubbing_withSettingsAPIAndStubbing_name() { + /* Given */ + val mock = mock<Methods>(name = "myName") { + on { nullableStringResult() } doReturn "foo" + } + + /* When */ + val result = mock.nullableStringResult() + + /* Then */ + expect(result).toBe("foo") + } + + @Test + fun mockStubbing_withSettingsAPI_defaultAnswer() { + /* Given */ + val mock = mock<Methods>(defaultAnswer = Mockito.RETURNS_MOCKS) {} + + /* When */ + val result = mock.nonDefaultReturnType() + + /* Then */ + expect(result).toNotBeNull() + } + + @Test + fun mockStubbing_withSettingsAPI_serializable() { + /* Given */ + val mock = mock<Methods>(serializable = true) {} + + /* Then */ + expect(mock).toBeInstanceOf<Serializable>() + } + + @Test + fun mockStubbing_withSettingsAPI_serializableMode() { + /* Given */ + val mock = mock<Methods>(serializableMode = BASIC) {} + + /* Then */ + expect(mock).toBeInstanceOf<Serializable>() + } + + @Test + fun mockStubbing_withSettingsAPI_verboseLogging() { + /* Given */ + val out = mock<PrintStream>() + System.setOut(out) + val mock = mock<Methods>(verboseLogging = true) {} + + try { + /* When */ + verify(mock).stringResult() + fail("Expected an exception") + } catch (e: WantedButNotInvoked) { + /* Then */ + verify(out).println("methods.stringResult();") + } + } + + @Test + fun mockStubbing_withSettingsAPI_invocationListeners() { + /* Given */ + var bool = false + val mock = mock<Methods>(invocationListeners = arrayOf(InvocationListener { bool = true })) {} + + /* When */ + mock.stringResult() + + /* Then */ + expect(bool).toHold() + } + + @Test + fun mockStubbing_withSettingsAPI_stubOnly() { + /* Given */ + val mock = mock<Methods>(stubOnly = true) {} + + /* Expect */ + expectErrorWithMessage("is a stubOnly() mock") on { + + /* When */ + verify(mock).stringResult() + } + } + + @Test + fun mockStubbing_withSettingsAPI_useConstructor() { + /* Given */ + expectErrorWithMessage("Unable to create mock instance of type ") on { + mock<ThrowingConstructor>(useConstructor = parameterless()) {} + } + } + + private interface MyInterface + private open class MyClass +}
\ No newline at end of file diff --git a/tests/src/test/kotlin/test/OngoingStubbingTest.kt b/tests/src/test/kotlin/test/OngoingStubbingTest.kt new file mode 100644 index 0000000..3c9268e --- /dev/null +++ b/tests/src/test/kotlin/test/OngoingStubbingTest.kt @@ -0,0 +1,340 @@ +package test + +import com.nhaarman.expect.expect +import com.nhaarman.expect.expectErrorWithMessage +import com.nhaarman.expect.fail +import org.junit.Assume.assumeFalse +import org.junit.Test +import org.mockito.Mockito +import org.mockito.exceptions.misusing.UnfinishedStubbingException +import org.mockito.kotlin.* +import org.mockito.stubbing.Answer +import kotlin.check + +class OngoingStubbingTest : TestBase() { + + @Test + fun testOngoingStubbing_methodCall() { + /* Given */ + val mock = mock<Open>() + mock<Open> { + on(mock.stringResult()).doReturn("A") + } + + /* When */ + val result = mock.stringResult() + + /* Then */ + expect(result).toBe("A") + } + + @Test + fun testOngoingStubbing_builder() { + /* Given */ + val mock = mock<Methods> { mock -> + on { builderMethod() } doReturn mock + } + + /* When */ + val result = mock.builderMethod() + + /* Then */ + expect(result).toBeTheSameAs(mock) + } + + @Test + fun testOngoingStubbing_nullable() { + /* Given */ + val mock = mock<Methods> { + on { nullableStringResult() } doReturn "Test" + } + + /* When */ + val result = mock.nullableStringResult() + + /* Then */ + expect(result).toBe("Test") + } + + @Test + fun testOngoingStubbing_doThrow() { + /* Given */ + val mock = mock<Methods> { + on { builderMethod() } doThrow IllegalArgumentException() + } + + try { + /* When */ + mock.builderMethod() + fail("No exception thrown") + } catch (e: IllegalArgumentException) { + } + } + + @Test + fun testOngoingStubbing_doThrowClass() { + /* Given */ + val mock = mock<Methods> { + on { builderMethod() } doThrow IllegalArgumentException::class + } + + try { + /* When */ + mock.builderMethod() + fail("No exception thrown") + } catch (e: IllegalArgumentException) { + } + } + + @Test + fun testOngoingStubbing_doThrowVarargs() { + /* Given */ + val mock = mock<Methods> { + on { builderMethod() }.doThrow( + IllegalArgumentException(), + UnsupportedOperationException() + ) + } + + try { + /* When */ + mock.builderMethod() + fail("No exception thrown") + } catch (e: IllegalArgumentException) { + } + + try { + /* When */ + mock.builderMethod() + fail("No exception thrown") + } catch (e: UnsupportedOperationException) { + } + } + + @Test + fun testOngoingStubbing_doThrowClassVarargs() { + /* Given */ + val mock = mock<Methods> { + on { builderMethod() }.doThrow( + IllegalArgumentException::class, + UnsupportedOperationException::class + ) + } + + try { + /* When */ + mock.builderMethod() + fail("No exception thrown") + } catch (e: IllegalArgumentException) { + } + + try { + /* When */ + mock.builderMethod() + fail("No exception thrown") + } catch (e: UnsupportedOperationException) { + } + } + + @Test + fun testOngoingStubbing_doAnswer_lambda() { + /* Given */ + val mock = mock<Methods> { + on { stringResult() } doAnswer { "result" } + } + + /* When */ + val result = mock.stringResult() + + /* Then */ + expect(result).toBe("result") + } + + @Test + fun testOngoingStubbing_doAnswer_instance() { + /* Given */ + val mock = mock<Methods> { + on { stringResult() } doAnswer Answer<String> { "result" } + } + + /* When */ + val result = mock.stringResult() + + /* Then */ + expect(result).toBe("result") + } + + @Test + fun testOngoingStubbing_doAnswer_returnsSelf() { + /* Given */ + val mock = mock<Methods> { + on { builderMethod() } doAnswer Mockito.RETURNS_SELF + } + + /* When */ + val result = mock.builderMethod() + + /* Then */ + expect(result).toBe(mock) + } + + @Test + fun testOngoingStubbing_doAnswer_withArgument() { + /* Given */ + val mock = mock<Methods> { + on { stringResult(any()) } doAnswer { "${it.arguments[0]}-result" } + } + + /* When */ + val result = mock.stringResult("argument") + + /* Then */ + expect(result).toBe("argument-result") + } + + @Test + fun testMockStubbingAfterCreatingMock() { + val mock = mock<Methods>() + + //create stub after creation of mock + mock.stub { + on { stringResult() } doReturn "result" + } + + /* When */ + val result = mock.stringResult() + + /* Then */ + expect(result).toBe("result") + } + + @Test + fun testOverrideDefaultStub() { + /* Given mock with stub */ + val mock = mock<Methods> { + on { stringResult() } doReturn "result1" + } + + /* override stub */ + mock.stub { + on { stringResult() } doReturn "result2" + } + + /* When */ + val result = mock.stringResult() + + /* Then */ + expect(result).toBe("result2") + } + + + @Test + fun stubbingTwiceWithArgumentMatchers() { + /* When */ + val mock = mock<Methods> { + on { stringResult(argThat { this == "A" }) } doReturn "A" + on { stringResult(argThat { this == "B" }) } doReturn "B" + } + + /* Then */ + expect(mock.stringResult("A")).toBe("A") + expect(mock.stringResult("B")).toBe("B") + } + + @Test + fun stubbingTwiceWithCheckArgumentMatchers_throwsException() { + /* Expect */ + expectErrorWithMessage("null").on { + mock<Methods> { + on { stringResult(check { }) } doReturn "A" + on { stringResult(check { }) } doReturn "B" + } + } + } + + @Test + fun doReturn_withSingleItemList() { + /* Given */ + val mock = mock<Open> { + on { stringResult() } doReturnConsecutively listOf("a", "b") + } + + /* Then */ + expect(mock.stringResult()).toBe("a") + expect(mock.stringResult()).toBe("b") + } + + @Test + fun doReturn_throwsNPE() { + assumeFalse(mockMakerInlineEnabled()) + expectErrorWithMessage("look at the stack trace below") on { + + /* When */ + mock<Open> { + on { throwsNPE() } doReturn "result" + } + } + } + + @Test + fun doReturn_withGenericIntReturnType_on() { + /* Expect */ + expectErrorWithMessage("onGeneric") on { + + /* When */ + mock<GenericMethods<Int>> { + on { genericMethod() } doReturn 2 + } + } + } + + @Test + fun doReturn_withGenericIntReturnType_onGeneric() { + /* Given */ + val mock = mock<GenericMethods<Int>> { + onGeneric { genericMethod() } doReturn 2 + } + + /* Then */ + expect(mock.genericMethod()).toBe(2) + } + + @Test + fun doReturn_withGenericNullableReturnType_onGeneric() { + val m = mock<GenericMethods<String>> { + onGeneric { nullableReturnType() } doReturn "Test" + } + + expect(m.nullableReturnType()).toBe("Test") + } + + @Test + fun stubbingExistingMock() { + /* Given */ + val mock = mock<Methods>() + + /* When */ + stubbing(mock) { + on { stringResult() } doReturn "result" + } + + /* Then */ + expect(mock.stringResult()).toBe("result") + } + + @Test + fun testMockitoStackOnUnfinishedStubbing() { + /* Given */ + val mock = mock<Open>() + whenever(mock.stringResult()) + + /* When */ + try { + mock.stringResult() + } catch (e: UnfinishedStubbingException) { + /* Then */ + expect(e.message).toContain("Unfinished stubbing detected here:") + expect(e.message).toContain("-> at test.OngoingStubbingTest.testMockitoStackOnUnfinishedStubbing") + } + } +} diff --git a/tests/src/test/kotlin/test/SpyTest.kt b/tests/src/test/kotlin/test/SpyTest.kt new file mode 100644 index 0000000..500faee --- /dev/null +++ b/tests/src/test/kotlin/test/SpyTest.kt @@ -0,0 +1,141 @@ +package test + +/* + * The MIT License + * + * Copyright (c) 2016 Niek Haarman + * Copyright (c) 2007 Mockito contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +import com.nhaarman.expect.expect +import org.junit.After +import org.junit.Test +import org.mockito.Mockito +import org.mockito.kotlin.* +import java.util.* + +class SpyTest : TestBase() { + + private val interfaceInstance: MyInterface = MyClass() + private val openClassInstance: MyClass = MyClass() + private val closedClassInstance: ClosedClass = ClosedClass() + + @After + override fun tearDown() { + super.tearDown() + Mockito.validateMockitoUsage() + } + + @Test + fun spyInterfaceInstance() { + /* When */ + val result = spy(interfaceInstance) + + /* Then */ + expect(result).toNotBeNull() + } + + @Test + fun spyOpenClassInstance() { + /* When */ + val result = spy(openClassInstance) + + /* Then */ + expect(result).toNotBeNull() + } + + @Test + fun doReturnWithSpy() { + val date = spy(Date()) + doReturn(123L).whenever(date).time + expect(date.time).toBe(123L) + } + + @Test + fun doNothingWithSpy() { + val date = spy(Date(0)) + doNothing().whenever(date).time = 5L + date.time = 5L + expect(date.time).toBe(0L) + } + + @Test(expected = IllegalArgumentException::class) + fun doThrowWithSpy() { + val date = spy(Date(0)) + doThrow(IllegalArgumentException()).whenever(date).time + date.time + } + + @Test + fun doCallRealMethodWithSpy() { + val date = spy(Date(0)) + doReturn(123L).whenever(date).time + doCallRealMethod().whenever(date).time + expect(date.time).toBe(0L) + } + + @Test + fun doReturnWithDefaultInstanceSpyStubbing() { + val timeVal = 12L + + val dateSpy = spy<Date> { + on { time } doReturn timeVal + } + + expect(dateSpy.time).toBe(timeVal) + } + + @Test + fun doReturnWithSpyStubbing() { + val timeVal = 15L + + val dateSpy = spy(Date(0)) { + on { time } doReturn timeVal + } + + expect(dateSpy.time).toBe(timeVal) + } + + @Test + fun passAnyStringToSpy() { + /* Given */ + val my = spy(MyClass()) + + /* When */ + doReturn("mocked").whenever(my).foo(any()) + + /* Then */ + expect(my.foo("hello")).toBe("mocked") + } + + private interface MyInterface { + + fun foo(value: String): String + } + + private open class MyClass : MyInterface { + + override fun foo(value: String): String = value + } + + private class ClosedClass +} + diff --git a/tests/src/test/kotlin/test/StubberTest.kt b/tests/src/test/kotlin/test/StubberTest.kt new file mode 100644 index 0000000..eb6e28c --- /dev/null +++ b/tests/src/test/kotlin/test/StubberTest.kt @@ -0,0 +1,103 @@ +package test + +import com.nhaarman.expect.expect +import com.nhaarman.expect.expectErrorWithMessage +import org.junit.Test +import org.mockito.kotlin.* + +class StubberTest : TestBase() { + + @Test + fun testDoAnswer() { + val mock = mock<Methods>() + + doAnswer { "Test" } + .whenever(mock) + .stringResult() + + expect(mock.stringResult()).toBe("Test") + } + + @Test + fun testDoCallRealMethod() { + val mock = mock<Open>() + + doReturn("Test").whenever(mock).stringResult() + doCallRealMethod().whenever(mock).stringResult() + + expect(mock.stringResult()).toBe("Default") + } + + @Test + fun testDoNothing() { + val spy = spy(Open()) + val array = intArrayOf(3) + + doNothing().whenever(spy).modifiesContents(array) + spy.modifiesContents(array) + + expect(array[0]).toBe(3) + } + + @Test + fun testDoReturnValue() { + val mock = mock<Methods>() + + doReturn("test").whenever(mock).stringResult() + + expect(mock.stringResult()).toBe("test") + } + + @Test + fun testDoReturnNullValue() { + val mock = mock<Methods>() + + doReturn(null).whenever(mock).stringResult() + + expect(mock.stringResult()).toBeNull() + } + + @Test + fun testDoReturnNullValues() { + val mock = mock<Methods>() + + doReturn(null, null).whenever(mock).stringResult() + + expect(mock.stringResult()).toBeNull() + expect(mock.stringResult()).toBeNull() + } + + @Test + fun testDoReturnValues() { + val mock = mock<Methods>() + + doReturn("test", "test2").whenever(mock).stringResult() + + expect(mock.stringResult()).toBe("test") + expect(mock.stringResult()).toBe("test2") + } + + @Test + fun testDoThrowClass() { + val mock = mock<Open>() + + doThrow(IllegalStateException::class).whenever(mock).go() + + try { + mock.go() + throw AssertionError("Call should have thrown.") + } catch (e: IllegalStateException) { + } + } + + @Test + fun testDoThrow() { + val mock = mock<Open>() + + doThrow(IllegalStateException("test")).whenever(mock).go() + + expectErrorWithMessage("test").on { + mock.go() + } + } +}
\ No newline at end of file diff --git a/tests/src/test/kotlin/test/TestBase.kt b/tests/src/test/kotlin/test/TestBase.kt new file mode 100644 index 0000000..95c76ec --- /dev/null +++ b/tests/src/test/kotlin/test/TestBase.kt @@ -0,0 +1,11 @@ +package test + +import org.junit.After + +abstract class TestBase { + + @After + open fun tearDown() { + mockMakerInlineEnabled = null + } +}
\ No newline at end of file diff --git a/tests/src/test/kotlin/test/VerificationTest.kt b/tests/src/test/kotlin/test/VerificationTest.kt new file mode 100644 index 0000000..f2f92fd --- /dev/null +++ b/tests/src/test/kotlin/test/VerificationTest.kt @@ -0,0 +1,115 @@ +package test + +import com.nhaarman.expect.expect +import org.junit.Test +import org.mockito.exceptions.base.MockitoAssertionError +import org.mockito.kotlin.* +import org.mockito.kotlin.verify + +class VerificationTest : TestBase() { + + @Test + fun atLeastXInvocations() { + mock<Methods>().apply { + string("") + string("") + + verify(this, atLeast(2)).string(any()) + } + } + + @Test + fun testAtLeastOnce() { + mock<Methods>().apply { + string("") + string("") + + verify(this, atLeastOnce()).string(any()) + } + } + + @Test + fun atMostXInvocations() { + mock<Methods>().apply { + string("") + string("") + + verify(this, atMost(2)).string(any()) + } + } + + @Test + fun testCalls() { + mock<Methods>().apply { + string("") + string("") + + inOrder(this).verify(this, calls(2)).string(any()) + } + } + + @Test + fun testInOrderWithLambda() { + /* Given */ + val a = mock<() -> Unit>() + val b = mock<() -> Unit>() + + /* When */ + b() + a() + + /* Then */ + inOrder(a, b) { + verify(b).invoke() + verify(a).invoke() + } + } + + @Test + fun testInOrderWithReceiver() { + /* Given */ + val mock = mock<Methods>() + + /* When */ + mock.string("") + mock.int(0) + + /* Then */ + mock.inOrder { + verify().string(any()) + verify().int(any()) + verifyNoMoreInteractions() + } + } + + @Test + fun testClearInvocations() { + val mock = mock<Methods>().apply { + string("") + } + + clearInvocations(mock) + + verify(mock, never()).string(any()) + } + + @Test + fun testDescription() { + try { + mock<Methods>().apply { + verify(this, description("Test")).string(any()) + } + throw AssertionError("Verify should throw Exception.") + } catch (e: MockitoAssertionError) { + expect(e.message).toContain("Test") + } + } + + @Test + fun testAfter() { + mock<Methods>().apply { + int(3) + verify(this, after(10)).int(3) + } + } +}
\ No newline at end of file diff --git a/tests/src/test/kotlin/test/VerifyTest.kt b/tests/src/test/kotlin/test/VerifyTest.kt new file mode 100644 index 0000000..0a93832 --- /dev/null +++ b/tests/src/test/kotlin/test/VerifyTest.kt @@ -0,0 +1,96 @@ +package test + +import org.mockito.kotlin.any +import org.mockito.kotlin.mock +import org.mockito.kotlin.verify +import org.junit.Test +import org.mockito.exceptions.verification.TooLittleActualInvocations +import org.mockito.exceptions.verification.junit.ArgumentsAreDifferent + +class VerifyTest : TestBase() { + + @Test + fun verify0Calls() { + val iface = mock<TestInterface>() + + verify(iface) { + 0 * { call(any()) } + } + } + + @Test + fun verifyNCalls() { + val iface = mock<TestInterface>() + + iface.call(42) + iface.call(42) + + verify(iface) { + 2 * { call(42) } + } + } + + @Test(expected = TooLittleActualInvocations::class) + fun verifyFailsWithWrongCount() { + val iface = mock<TestInterface>() + + iface.call(0) + + verify(iface) { + 2 * { call(0) } + } + } + + @Test(expected = ArgumentsAreDifferent::class) + fun verifyFailsWithWrongArg() { + val iface = mock<TestInterface>() + + iface.call(3) + + verify(iface) { + 1 * { call(0) } + } + } + + @Test + fun verifyDefaultArgs_firstParameter() { + /* Given */ + val m = mock<TestInterface>() + + /* When */ + m.defaultArgs(a = 2) + + /* Then */ + verify(m).defaultArgs(2) + } + + @Test + fun verifyDefaultArgs_secondParameter() { + /* Given */ + val m = mock<TestInterface>() + + /* When */ + m.defaultArgs(b = 2) + + /* Then */ + verify(m).defaultArgs(b = 2) + } + + @Test + fun verifyDefaultArgs_verifyDefaultValue() { + /* Given */ + val m = mock<TestInterface>() + + /* When */ + m.defaultArgs(b = 2) + + /* Then */ + verify(m).defaultArgs(a = 3, b = 2) + } + + interface TestInterface { + fun call(arg: Int) + + fun defaultArgs(a: Int = 3, b: Int = 42) + } +}
\ No newline at end of file diff --git a/tests/src/test/kotlin/test/createinstance/NullCasterTest.kt b/tests/src/test/kotlin/test/createinstance/NullCasterTest.kt new file mode 100644 index 0000000..6d160c7 --- /dev/null +++ b/tests/src/test/kotlin/test/createinstance/NullCasterTest.kt @@ -0,0 +1,31 @@ +package test.createinstance + +import com.nhaarman.expect.expect +import org.mockito.kotlin.internal.createInstance +import org.junit.Test +import test.TestBase + + +class NullCasterTest : TestBase() { + + @Test + fun createInstance() { + /* When */ + val result = createInstance(String::class) + + /* Then */ + expect(result).toBeNull() + } + + @Test + fun kotlinAcceptsNullValue() { + /* Given */ + val s: String = createInstance(String::class) + + /* When */ + acceptNonNullableString(s) + } + + private fun acceptNonNullableString(@Suppress("UNUSED_PARAMETER") s: String) { + } +} diff --git a/tests/src/test/kotlin/test/inline/UsingMockMakerInlineTest.kt b/tests/src/test/kotlin/test/inline/UsingMockMakerInlineTest.kt new file mode 100644 index 0000000..b03d77e --- /dev/null +++ b/tests/src/test/kotlin/test/inline/UsingMockMakerInlineTest.kt @@ -0,0 +1,116 @@ +/* + * The MIT License + * + * Copyright (c) 2016 Ian J. De Silva + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +import com.nhaarman.expect.expect +import org.junit.Assume.assumeTrue +import org.junit.Before +import org.junit.Test +import org.mockito.kotlin.* +import test.mockMakerInlineEnabled +import java.io.IOException +import java.math.BigInteger + +class UsingMockMakerInlineTest { + + class ClassToBeMocked { + + fun doSomething(@Suppress("UNUSED_PARAMETER") c: ClassToBeMocked) { + } + + fun doSomethingElse(value: BigInteger): BigInteger { + return value.plus(BigInteger.ONE) + } + } + + @Before + fun setup() { + mockMakerInlineEnabled = null + assumeTrue(mockMakerInlineEnabled()) + } + + @Test + fun mockClosedClass() { + /* When */ + val result = mock<ClassToBeMocked>() + + /* Then */ + expect(result).toNotBeNull() + } + + @Test + fun anyClosedClass() { + /* Given */ + val mock = mock<ClassToBeMocked>() + + /* When */ + mock.doSomething(mock) + + /* Then */ + verify(mock).doSomething(any()) + } + + @Test + fun mockClosedFunction_mockStubbing() { + /* Given */ + val mock = mock<ClassToBeMocked> { + on { doSomethingElse(any()) } doReturn (BigInteger.ONE) + } + + /* When */ + val result = mock.doSomethingElse(BigInteger.TEN) + + /* Then */ + expect(result).toBe(BigInteger.ONE) + } + + @Test + fun mockClosedFunction_whenever() { + /* Given */ + val mock = mock<ClassToBeMocked>() + whenever(mock.doSomethingElse(any())).doReturn(BigInteger.ONE) + + /* When */ + val result = mock.doSomethingElse(BigInteger.TEN) + + /* Then */ + expect(result).toBe(BigInteger.ONE) + } + + /** https://github.com/nhaarman/mockito-kotlin/issues/27 */ + @Test + fun anyThrowableWithSingleThrowableConstructor() { + mock<Methods>().apply { + throwableClass(ThrowableClass(IOException())) + verify(this).throwableClass(any()) + } + } + + interface Methods { + + fun throwableClass(t: ThrowableClass) + } + + class ThrowableClass(cause: Throwable) : Throwable(cause) + +} |