├── version.properties
├── gradle.properties
├── tests
├── settings.gradle
├── gradle.properties
├── src
│ └── test
│ │ └── kotlin
│ │ └── test
│ │ ├── TestBase.kt
│ │ ├── MockMaker.kt
│ │ ├── createinstance
│ │ └── NullCasterTest.kt
│ │ ├── LenientStubberTest.kt
│ │ ├── VerifyTest.kt
│ │ ├── VerificationTest.kt
│ │ ├── AdditionalMatchersTest.kt
│ │ ├── StubberTest.kt
│ │ ├── EqTest.kt
│ │ ├── Classes.kt
│ │ ├── BDDMockitoTest.kt
│ │ ├── inline
│ │ └── UsingMockMakerInlineTest.kt
│ │ ├── SpyTest.kt
│ │ ├── ArgumentCaptorTest.kt
│ │ ├── MatchersTest.kt
│ │ ├── OngoingStubbingTest.kt
│ │ └── MockingTest.kt
├── README.md
└── build.gradle
├── ops
├── org.mockito.plugins.MockMaker
└── mockMakerInline.sh
├── settings.gradle
├── gradle
├── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
└── publishing.gradle
├── .github
├── PULL_REQUEST_TEMPLATE.md
└── workflows
│ └── ci.yml
├── .idea
├── codeStyles
│ ├── codeStyleConfig.xml
│ └── Project.xml
├── copyright
│ ├── profiles_settings.xml
│ └── MIT.xml
└── inspectionProfiles
│ └── Project_Default.xml
├── .gitignore
├── RELEASING.md
├── LICENSE
├── mockito-kotlin
├── src
│ ├── main
│ │ └── kotlin
│ │ │ └── org
│ │ │ └── mockito
│ │ │ └── kotlin
│ │ │ ├── MockitoKotlinException.kt
│ │ │ ├── Mockito.kt
│ │ │ ├── LenientStubber.kt
│ │ │ ├── VerifyScope.kt
│ │ │ ├── internal
│ │ │ ├── KInOrderDecorator.kt
│ │ │ ├── CreateInstance.kt
│ │ │ └── SuspendableAnswer.kt
│ │ │ ├── KInOrder.kt
│ │ │ ├── Spying.kt
│ │ │ ├── Stubber.kt
│ │ │ ├── KStubbing.kt
│ │ │ ├── OngoingStubbing.kt
│ │ │ ├── BDDMockito.kt
│ │ │ ├── Matchers.kt
│ │ │ ├── AdditionalMatchers.kt
│ │ │ ├── ArgumentCaptor.kt
│ │ │ ├── Verification.kt
│ │ │ └── Mocking.kt
│ └── test
│ │ └── kotlin
│ │ ├── org
│ │ └── mockito
│ │ │ └── kotlin
│ │ │ └── BDDMockitoKtTest.kt
│ │ └── test
│ │ └── CoroutinesTest.kt
└── build.gradle
├── README.md
├── gradlew.bat
└── gradlew
/version.properties:
--------------------------------------------------------------------------------
1 | tagPrefix=
2 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | isRelease=false
2 |
--------------------------------------------------------------------------------
/tests/settings.gradle:
--------------------------------------------------------------------------------
1 | includeBuild '..'
2 |
--------------------------------------------------------------------------------
/ops/org.mockito.plugins.MockMaker:
--------------------------------------------------------------------------------
1 | mock-maker-inline
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include 'mockito-kotlin'
2 | includeBuild 'tests'
3 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Mustafa-Hassan2001/mockito-kotlin/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/.github/PULL_REQUEST_TEMPLATE.md:
--------------------------------------------------------------------------------
1 | Thank you for submitting a pull request! But first:
2 |
3 | - [ ] Can you back your code up with tests?
4 |
--------------------------------------------------------------------------------
/tests/gradle.properties:
--------------------------------------------------------------------------------
1 | # Default version for the :tests module for Kotlin StdLib / KGP.
2 | # See https://github.com/mockito/mockito-kotlin#testing for more.
3 | testKotlinVersion=1.9.20
4 |
--------------------------------------------------------------------------------
/.idea/codeStyles/codeStyleConfig.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .gradle
2 | build/
3 | out/
4 | repo
5 |
6 | # Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored)
7 | !gradle-wrapper.jar
8 |
9 | # intelliJ
10 | .idea/
11 | *.iml
12 |
13 | *.orig
14 |
--------------------------------------------------------------------------------
/.idea/copyright/profiles_settings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/tests/src/test/kotlin/test/TestBase.kt:
--------------------------------------------------------------------------------
1 | package test
2 |
3 | import org.junit.After
4 |
5 | abstract class TestBase {
6 |
7 | @After
8 | open fun tearDown() {
9 | mockMakerInlineEnabled = null
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionPath=wrapper/dists
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.1-bin.zip
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 |
--------------------------------------------------------------------------------
/ops/mockMakerInline.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | set -ev
4 |
5 | if [ ${MOCK_MAKER} = "mock-maker-inline" ]; then
6 | mkdir -p tests/src/test/resources/mockito-extensions
7 | cp ops/org.mockito.plugins.MockMaker tests/src/test/resources/mockito-extensions/
8 | fi
9 |
10 | exit 0;
11 |
12 |
--------------------------------------------------------------------------------
/tests/README.md:
--------------------------------------------------------------------------------
1 | Mockito-Kotlin tests
2 | ====================
3 |
4 | Tests should be placed in this module.
5 | CI is set up to execute tests for all major versions of Kotlin,
6 | whilst keeping the library version on the latest version.
7 | This ensures the library is backwards compatible for all Kotlin versions.
8 |
--------------------------------------------------------------------------------
/.idea/inspectionProfiles/Project_Default.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/tests/src/test/kotlin/test/MockMaker.kt:
--------------------------------------------------------------------------------
1 | package test
2 |
3 | import org.mockito.internal.configuration.plugins.Plugins
4 | import org.mockito.internal.creation.bytebuddy.InlineByteBuddyMockMaker
5 |
6 | internal var mockMakerInlineEnabled: Boolean? = null
7 |
8 | internal fun mockMakerInlineEnabled(): Boolean {
9 | return mockMakerInlineEnabled ?: (Plugins.getMockMaker() is InlineByteBuddyMockMaker)
10 | }
11 |
--------------------------------------------------------------------------------
/RELEASING.md:
--------------------------------------------------------------------------------
1 | # Releasing
2 |
3 | 1. Every change on the main development branch is released as -SNAPSHOT version
4 | to Sonatype snapshot repo at https://s01.oss.sonatype.org/content/repositories/snapshots/org/mockito/kotlin/mockito-kotlin.
5 | 2. In order to release a non-snapshot version to Maven Central push an annotated tag, for example:
6 | ```
7 | git tag -a -m "Release 3.4.5" 3.4.5
8 | git push origin 3.4.5
9 | ```
10 | 3. At the moment, you **may not create releases from GitHub Web UI**.
11 | Doing so will make the CI build fail because the CI creates the changelog and posts to GitHub releases.
12 | In the future supporting this would be nice but currently please make releases by pushing from CLI.
13 |
--------------------------------------------------------------------------------
/tests/src/test/kotlin/test/createinstance/NullCasterTest.kt:
--------------------------------------------------------------------------------
1 | package test.createinstance
2 |
3 | import com.nhaarman.expect.expect
4 | import org.mockito.kotlin.internal.createInstance
5 | import org.junit.Test
6 | import test.TestBase
7 |
8 | class NullCasterTest : TestBase() {
9 |
10 | @Test
11 | fun createInstance() {
12 | /* When */
13 | val result = createInstance(String::class)
14 |
15 | /* Then */
16 | expect(result).toBeNull()
17 | }
18 |
19 | @Test
20 | fun kotlinAcceptsNullValue() {
21 | /* Given */
22 | val s: String = createInstance(String::class)
23 |
24 | /* When */
25 | acceptNonNullableString(s)
26 | }
27 |
28 | private fun acceptNonNullableString(@Suppress("UNUSED_PARAMETER") s: String) {
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/tests/build.gradle:
--------------------------------------------------------------------------------
1 | import org.jetbrains.kotlin.gradle.dsl.JvmTarget
2 | import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
3 |
4 | plugins {
5 | id "org.gradle.java"
6 | id "org.jetbrains.kotlin.jvm" version "${testKotlinVersion}"
7 | }
8 |
9 | logger.lifecycle "${project} uses Kotlin ${testKotlinVersion}"
10 |
11 | repositories {
12 | mavenCentral()
13 | }
14 |
15 | dependencies {
16 | implementation "org.mockito.kotlin:mockito-kotlin"
17 |
18 | implementation "org.jetbrains.kotlin:kotlin-stdlib"
19 |
20 | testImplementation 'junit:junit:4.13.2'
21 | testImplementation "com.nhaarman:expect.kt:1.0.1"
22 | }
23 |
24 | tasks.withType(KotlinCompile).configureEach {
25 | compilerOptions {
26 | jvmTarget.set(JvmTarget.JVM_11)
27 | targetCompatibility = "11"
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | The MIT License
2 |
3 | Copyright (c) 2016 Niek Haarman
4 | Copyright (c) 2007 Mockito contributors
5 |
6 | Permission is hereby granted, free of charge, to any person obtaining a copy
7 | of this software and associated documentation files (the "Software"), to deal
8 | in the Software without restriction, including without limitation the rights
9 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 | copies of the Software, and to permit persons to whom the Software is
11 | furnished to do so, subject to the following conditions:
12 |
13 | The above copyright notice and this permission notice shall be included in
14 | all copies or substantial portions of the Software.
15 |
16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 | THE SOFTWARE.
--------------------------------------------------------------------------------
/.idea/copyright/MIT.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/mockito-kotlin/src/main/kotlin/org/mockito/kotlin/MockitoKotlinException.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * The MIT License
3 | *
4 | * Copyright (c) 2018 Niek Haarman
5 | * Copyright (c) 2007 Mockito contributors
6 | *
7 | * Permission is hereby granted, free of charge, to any person obtaining a copy
8 | * of this software and associated documentation files (the "Software"), to deal
9 | * in the Software without restriction, including without limitation the rights
10 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 | * copies of the Software, and to permit persons to whom the Software is
12 | * furnished to do so, subject to the following conditions:
13 | *
14 | * The above copyright notice and this permission notice shall be included in
15 | * all copies or substantial portions of the Software.
16 | *
17 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23 | * THE SOFTWARE.
24 | */
25 |
26 | package org.mockito.kotlin
27 |
28 | class MockitoKotlinException(message: String?, cause: Throwable?) : RuntimeException(message, cause)
29 |
--------------------------------------------------------------------------------
/mockito-kotlin/build.gradle:
--------------------------------------------------------------------------------
1 | import org.jetbrains.kotlin.gradle.dsl.JvmTarget
2 | import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
3 |
4 | plugins {
5 | id "org.jetbrains.kotlin.jvm"
6 | id "org.jetbrains.dokka"
7 | }
8 | apply from: '../gradle/publishing.gradle'
9 |
10 | group = 'org.mockito.kotlin'
11 |
12 | repositories {
13 | mavenCentral()
14 | }
15 |
16 | dependencies {
17 | compileOnly "org.jetbrains.kotlin:kotlin-stdlib"
18 | compileOnly 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.0.0'
19 |
20 | api "org.mockito:mockito-core:5.7.0"
21 |
22 | testImplementation 'junit:junit:4.13.2'
23 | testImplementation 'com.nhaarman:expect.kt:1.0.1'
24 |
25 | testImplementation "org.jetbrains.kotlin:kotlin-stdlib"
26 | testImplementation "org.jetbrains.kotlin:kotlin-test"
27 | testImplementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.0'
28 |
29 | testImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.0.0"
30 | }
31 |
32 | dokkaHtml.configure {
33 | outputDirectory.set(file("$buildDir/javadoc"))
34 |
35 | dokkaSourceSets {
36 | named("main") {
37 | localDirectory.set(file("src/main/kotlin"))
38 | remoteUrl.set(new URL("https://github.com/nhaarman/mockito-kotlin/tree/master/mockito-kotlin/src/main/kotlin"))
39 | remoteLineSuffix.set("#L")
40 | }
41 | }
42 | }
43 |
44 | tasks.withType(KotlinCompile).configureEach {
45 | compilerOptions {
46 | jvmTarget.set(JvmTarget.JVM_11)
47 | targetCompatibility = "11"
48 | }
49 | }
50 |
51 | javadoc.dependsOn dokkaHtml
52 |
--------------------------------------------------------------------------------
/mockito-kotlin/src/main/kotlin/org/mockito/kotlin/Mockito.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * The MIT License
3 | *
4 | * Copyright (c) 2018 Niek Haarman
5 | * Copyright (c) 2007 Mockito contributors
6 | *
7 | * Permission is hereby granted, free of charge, to any person obtaining a copy
8 | * of this software and associated documentation files (the "Software"), to deal
9 | * in the Software without restriction, including without limitation the rights
10 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 | * copies of the Software, and to permit persons to whom the Software is
12 | * furnished to do so, subject to the following conditions:
13 | *
14 | * The above copyright notice and this permission notice shall be included in
15 | * all copies or substantial portions of the Software.
16 | *
17 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23 | * THE SOFTWARE.
24 | */
25 |
26 | package org.mockito.kotlin
27 |
28 | import org.mockito.MockingDetails
29 | import org.mockito.Mockito
30 |
31 | fun validateMockitoUsage() {
32 | Mockito.validateMockitoUsage()
33 | }
34 |
35 | fun reset(vararg mocks: T) {
36 | Mockito.reset(*mocks)
37 | }
38 |
39 | fun mockingDetails(toInspect: Any): MockingDetails {
40 | return Mockito.mockingDetails(toInspect)!!
41 | }
42 |
--------------------------------------------------------------------------------
/mockito-kotlin/src/main/kotlin/org/mockito/kotlin/LenientStubber.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * The MIT License
3 | *
4 | * Copyright (c) 2018 Niek Haarman
5 | * Copyright (c) 2007 Mockito contributors
6 | *
7 | * Permission is hereby granted, free of charge, to any person obtaining a copy
8 | * of this software and associated documentation files (the "Software"), to deal
9 | * in the Software without restriction, including without limitation the rights
10 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 | * copies of the Software, and to permit persons to whom the Software is
12 | * furnished to do so, subject to the following conditions:
13 | *
14 | * The above copyright notice and this permission notice shall be included in
15 | * all copies or substantial portions of the Software.
16 | *
17 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23 | * THE SOFTWARE.
24 | */
25 |
26 | package org.mockito.kotlin
27 |
28 | import org.mockito.stubbing.LenientStubber
29 | import org.mockito.stubbing.OngoingStubbing
30 |
31 | inline fun LenientStubber.whenever(methodCall: T): OngoingStubbing {
32 | return `when`(methodCall)
33 | }
34 |
35 | inline fun LenientStubber.whenever(methodCall: () -> T): OngoingStubbing {
36 | return whenever(methodCall())
37 | }
38 |
39 |
--------------------------------------------------------------------------------
/tests/src/test/kotlin/test/LenientStubberTest.kt:
--------------------------------------------------------------------------------
1 | package test
2 |
3 | import org.junit.Assert
4 | import org.junit.Rule
5 | import org.junit.Test
6 | import org.mockito.Mockito.lenient
7 | import org.mockito.junit.MockitoJUnit
8 | import org.mockito.junit.MockitoRule
9 | import org.mockito.kotlin.any
10 | import org.mockito.kotlin.doReturn
11 | import org.mockito.kotlin.mock
12 | import org.mockito.kotlin.whenever
13 | import org.mockito.quality.Strictness
14 |
15 | open class LenientStubberTest {
16 | @get:Rule
17 | val rule: MockitoRule = MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS)
18 |
19 | @Test
20 | fun unused_and_lenient_stubbings() {
21 | val mock = mock>()
22 | lenient().whenever(mock.add("one")).doReturn(true)
23 | whenever(mock[any()]).doReturn("hello")
24 |
25 | Assert.assertEquals("List should contain hello", "hello", mock[1])
26 | }
27 |
28 | @Test
29 | fun unused_and_lenient_stubbings_with_unit() {
30 | val mock = mock>()
31 | lenient().whenever { mock.add("one") }.doReturn(true)
32 | whenever(mock[any()]).doReturn("hello")
33 |
34 | Assert.assertEquals("List should contain hello", "hello", mock[1])
35 | }
36 |
37 | @Test
38 | fun unused_and_lenient_stubbings_with_nullable() {
39 | val mock = mock()
40 | lenient().whenever(mock.returnsNullableString()).doReturn(null)
41 | whenever(mock.returnsNonNullableString()).doReturn("hello")
42 |
43 | Assert.assertEquals("Should return hello", "hello", mock.returnsNonNullableString())
44 | }
45 |
46 | private class NullableToString {
47 | fun returnsNullableString(): String? = ""
48 | fun returnsNonNullableString(): String = ""
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/mockito-kotlin/src/main/kotlin/org/mockito/kotlin/VerifyScope.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * The MIT License
3 | *
4 | * Copyright (c) 2018 Niek Haarman
5 | * Copyright (c) 2007 Mockito contributors
6 | *
7 | * Permission is hereby granted, free of charge, to any person obtaining a copy
8 | * of this software and associated documentation files (the "Software"), to deal
9 | * in the Software without restriction, including without limitation the rights
10 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 | * copies of the Software, and to permit persons to whom the Software is
12 | * furnished to do so, subject to the following conditions:
13 | *
14 | * The above copyright notice and this permission notice shall be included in
15 | * all copies or substantial portions of the Software.
16 | *
17 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23 | * THE SOFTWARE.
24 | */
25 |
26 | package org.mockito.kotlin
27 |
28 | /**
29 | * Verify multiple calls on mock
30 | * Supports an easier to read style of
31 | *
32 | * ```
33 | * verify(mock) {
34 | * 2 * { call() }
35 | * }
36 | * ```
37 | */
38 | inline fun verify(mock: T, block: VerifyScope.() -> Unit) {
39 | VerifyScope(mock).block()
40 | }
41 |
42 | class VerifyScope(val mock: T) {
43 |
44 | operator inline fun Int.times(call: T.() -> Unit) {
45 | verify(mock, org.mockito.kotlin.times(this)).call()
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/mockito-kotlin/src/main/kotlin/org/mockito/kotlin/internal/KInOrderDecorator.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * The MIT License
3 | *
4 | * Copyright (c) 2018 Niek Haarman
5 | * Copyright (c) 2007 Mockito contributors
6 | *
7 | * Permission is hereby granted, free of charge, to any person obtaining a copy
8 | * of this software and associated documentation files (the "Software"), to deal
9 | * in the Software without restriction, including without limitation the rights
10 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 | * copies of the Software, and to permit persons to whom the Software is
12 | * furnished to do so, subject to the following conditions:
13 | *
14 | * The above copyright notice and this permission notice shall be included in
15 | * all copies or substantial portions of the Software.
16 | *
17 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23 | * THE SOFTWARE.
24 | */
25 |
26 | package org.mockito.kotlin.internal
27 |
28 | import kotlinx.coroutines.runBlocking
29 | import org.mockito.InOrder
30 | import org.mockito.kotlin.KInOrder
31 | import org.mockito.verification.VerificationMode
32 |
33 | class KInOrderDecorator(private val inOrder: InOrder) : KInOrder, InOrder by inOrder {
34 | override fun verifyBlocking(mock: T, f: suspend T.() -> Unit) {
35 | val m = verify(mock)
36 | runBlocking { m.f() }
37 | }
38 |
39 | override fun verifyBlocking(mock: T, mode: VerificationMode, f: suspend T.() -> Unit) {
40 | val m = verify(mock, mode)
41 | runBlocking { m.f() }
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/mockito-kotlin/src/main/kotlin/org/mockito/kotlin/KInOrder.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * The MIT License
3 | *
4 | * Copyright (c) 2018 Niek Haarman
5 | * Copyright (c) 2007 Mockito contributors
6 | *
7 | * Permission is hereby granted, free of charge, to any person obtaining a copy
8 | * of this software and associated documentation files (the "Software"), to deal
9 | * in the Software without restriction, including without limitation the rights
10 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 | * copies of the Software, and to permit persons to whom the Software is
12 | * furnished to do so, subject to the following conditions:
13 | *
14 | * The above copyright notice and this permission notice shall be included in
15 | * all copies or substantial portions of the Software.
16 | *
17 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23 | * THE SOFTWARE.
24 | */
25 |
26 | package org.mockito.kotlin
27 |
28 | import org.mockito.InOrder
29 | import org.mockito.verification.VerificationMode
30 |
31 | interface KInOrder : InOrder {
32 | /**
33 | * Verifies certain suspending behavior happened once in order.
34 | *
35 | * Warning: Only one method call can be verified in the function.
36 | * Subsequent method calls are ignored!
37 | */
38 | fun verifyBlocking(mock: T, f: suspend T.() -> Unit)
39 |
40 | /**
41 | * Verifies certain suspending behavior happened at least once / exact number of times / never in order.
42 | *
43 | * Warning: Only one method call can be verified in the function.
44 | * Subsequent method calls are ignored!
45 | */
46 | fun verifyBlocking(mock: T, mode: VerificationMode, f: suspend T.() -> Unit)
47 | }
48 |
--------------------------------------------------------------------------------
/mockito-kotlin/src/main/kotlin/org/mockito/kotlin/internal/CreateInstance.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * The MIT License
3 | *
4 | * Copyright (c) 2018 Niek Haarman
5 | * Copyright (c) 2007 Mockito contributors
6 | *
7 | * Permission is hereby granted, free of charge, to any person obtaining a copy
8 | * of this software and associated documentation files (the "Software"), to deal
9 | * in the Software without restriction, including without limitation the rights
10 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 | * copies of the Software, and to permit persons to whom the Software is
12 | * furnished to do so, subject to the following conditions:
13 | *
14 | * The above copyright notice and this permission notice shall be included in
15 | * all copies or substantial portions of the Software.
16 | *
17 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23 | * THE SOFTWARE.
24 | */
25 |
26 | package org.mockito.kotlin.internal
27 |
28 | import kotlin.reflect.KClass
29 |
30 | inline fun createInstance(): T {
31 | return when (T::class) {
32 | Boolean::class -> false as T
33 | Byte::class -> 0.toByte() as T
34 | Char::class -> 0.toChar() as T
35 | Short::class -> 0.toShort() as T
36 | Int::class -> 0 as T
37 | Long::class -> 0L as T
38 | Float::class -> 0f as T
39 | Double::class -> 0.0 as T
40 | else -> createInstance(T::class)
41 | }
42 | }
43 |
44 | fun createInstance(@Suppress("UNUSED_PARAMETER") kClass: KClass): T {
45 | return castNull()
46 | }
47 |
48 | /**
49 | * Uses a quirk in the bytecode generated by Kotlin
50 | * to cast [null] to a non-null type.
51 | *
52 | * See https://youtrack.jetbrains.com/issue/KT-8135.
53 | */
54 | @Suppress("UNCHECKED_CAST")
55 | private fun castNull(): T = null as T
56 |
--------------------------------------------------------------------------------
/tests/src/test/kotlin/test/VerifyTest.kt:
--------------------------------------------------------------------------------
1 | package test
2 |
3 | import org.mockito.kotlin.any
4 | import org.mockito.kotlin.mock
5 | import org.mockito.kotlin.verify
6 | import org.junit.Test
7 | import org.mockito.exceptions.verification.TooFewActualInvocations
8 | import org.mockito.exceptions.verification.junit.ArgumentsAreDifferent
9 |
10 | class VerifyTest : TestBase() {
11 |
12 | @Test
13 | fun verify0Calls() {
14 | val iface = mock()
15 |
16 | verify(iface) {
17 | 0 * { call(any()) }
18 | }
19 | }
20 |
21 | @Test
22 | fun verifyNCalls() {
23 | val iface = mock()
24 |
25 | iface.call(42)
26 | iface.call(42)
27 |
28 | verify(iface) {
29 | 2 * { call(42) }
30 | }
31 | }
32 |
33 | @Test(expected = TooFewActualInvocations::class)
34 | fun verifyFailsWithWrongCount() {
35 | val iface = mock()
36 |
37 | iface.call(0)
38 |
39 | verify(iface) {
40 | 2 * { call(0) }
41 | }
42 | }
43 |
44 | @Test(expected = ArgumentsAreDifferent::class)
45 | fun verifyFailsWithWrongArg() {
46 | val iface = mock()
47 |
48 | iface.call(3)
49 |
50 | verify(iface) {
51 | 1 * { call(0) }
52 | }
53 | }
54 |
55 | @Test
56 | fun verifyDefaultArgs_firstParameter() {
57 | /* Given */
58 | val m = mock()
59 |
60 | /* When */
61 | m.defaultArgs(a = 2)
62 |
63 | /* Then */
64 | verify(m).defaultArgs(2)
65 | }
66 |
67 | @Test
68 | fun verifyDefaultArgs_secondParameter() {
69 | /* Given */
70 | val m = mock()
71 |
72 | /* When */
73 | m.defaultArgs(b = 2)
74 |
75 | /* Then */
76 | verify(m).defaultArgs(b = 2)
77 | }
78 |
79 | @Test
80 | fun verifyDefaultArgs_verifyDefaultValue() {
81 | /* Given */
82 | val m = mock()
83 |
84 | /* When */
85 | m.defaultArgs(b = 2)
86 |
87 | /* Then */
88 | verify(m).defaultArgs(a = 3, b = 2)
89 | }
90 |
91 | interface TestInterface {
92 | fun call(arg: Int)
93 |
94 | fun defaultArgs(a: Int = 3, b: Int = 42)
95 | }
96 | }
97 |
--------------------------------------------------------------------------------
/mockito-kotlin/src/main/kotlin/org/mockito/kotlin/internal/SuspendableAnswer.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * The MIT License
3 | *
4 | * Copyright (c) 2018 Niek Haarman
5 | * Copyright (c) 2007 Mockito contributors
6 | *
7 | * Permission is hereby granted, free of charge, to any person obtaining a copy
8 | * of this software and associated documentation files (the "Software"), to deal
9 | * in the Software without restriction, including without limitation the rights
10 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 | * copies of the Software, and to permit persons to whom the Software is
12 | * furnished to do so, subject to the following conditions:
13 | *
14 | * The above copyright notice and this permission notice shall be included in
15 | * all copies or substantial portions of the Software.
16 | *
17 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23 | * THE SOFTWARE.
24 | */
25 |
26 | package org.mockito.kotlin.internal
27 |
28 | import org.mockito.internal.invocation.InterceptedInvocation
29 | import org.mockito.invocation.InvocationOnMock
30 | import org.mockito.stubbing.Answer
31 | import kotlin.coroutines.Continuation
32 | import kotlin.coroutines.intrinsics.startCoroutineUninterceptedOrReturn
33 |
34 | /**
35 | * This class properly wraps suspendable lambda into [Answer]
36 | */
37 | @Suppress("UNCHECKED_CAST")
38 | internal class SuspendableAnswer(
39 | private val body: suspend (InvocationOnMock) -> T?
40 | ) : Answer {
41 | override fun answer(invocation: InvocationOnMock?): T {
42 | //all suspend functions/lambdas has Continuation as the last argument.
43 | //InvocationOnMock does not see last argument
44 | val rawInvocation = invocation as InterceptedInvocation
45 | val continuation = rawInvocation.rawArguments.last() as Continuation
46 |
47 | // https://youtrack.jetbrains.com/issue/KT-33766#focus=Comments-27-3707299.0-0
48 | return body.startCoroutineUninterceptedOrReturn(invocation, continuation) as T
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/gradle/publishing.gradle:
--------------------------------------------------------------------------------
1 | //Maven publication plugins & configuration
2 | apply plugin: 'maven-publish'
3 |
4 | task javadocJar(type: Jar, dependsOn: javadoc) {
5 | archiveClassifier = 'javadoc'
6 | from 'build/javadoc'
7 | }
8 |
9 | task sourceJar(type: Jar) {
10 | archiveClassifier = "sources"
11 | from sourceSets.main.allSource
12 | }
13 |
14 | publishing {
15 | publications {
16 | javaLibrary(MavenPublication) {
17 | artifactId 'mockito-kotlin'
18 |
19 | from components.java
20 |
21 | artifact sourceJar
22 | artifact javadocJar
23 |
24 | pom.withXml {
25 | def root = asNode()
26 | root.appendNode('name', 'Mockito-Kotlin')
27 | root.appendNode('description', 'Using Mockito with Kotlin.')
28 | root.appendNode('url', 'https://github.com/mockito/mockito-kotlin')
29 |
30 | def scm = root.appendNode('scm')
31 | scm.appendNode('url', 'scm:git@github.com:mockito/mockito-kotlin.git')
32 |
33 | def licenses = root.appendNode('licenses')
34 | def mitLicense = licenses.appendNode('license')
35 | mitLicense.appendNode('name', 'MIT')
36 |
37 | def developers = root.appendNode('developers')
38 | def nhaarman = developers.appendNode('developer')
39 | nhaarman.appendNode('id', 'nhaarman')
40 | nhaarman.appendNode('name', 'Niek Haarman')
41 | }
42 | }
43 | }
44 |
45 | //useful for testing - running "publish" will create artifacts/pom in a local dir
46 | repositories { maven { url = "$rootProject.buildDir/repo" } }
47 | }
48 |
49 | clean {
50 | delete "$rootProject.buildDir/repo"
51 | }
52 |
53 | // Avoid generation of the module metadata so that we don't have to publish an additional file
54 | // and keep the build logic simple.
55 | tasks.withType(GenerateModuleMetadata) {
56 | enabled = false
57 | }
58 |
59 | //fleshes out problems with Maven pom generation when building
60 | tasks.build.dependsOn('publishJavaLibraryPublicationToMavenLocal')
61 |
62 | apply plugin: 'signing' //https://docs.gradle.org/current/userguide/signing_plugin.html
63 | signing {
64 | if (System.getenv("PGP_KEY")) {
65 | useInMemoryPgpKeys(System.getenv("PGP_KEY"), System.getenv("PGP_PWD"))
66 | sign publishing.publications.javaLibrary
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/mockito-kotlin/src/main/kotlin/org/mockito/kotlin/Spying.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * The MIT License
3 | *
4 | * Copyright (c) 2018 Niek Haarman
5 | * Copyright (c) 2007 Mockito contributors
6 | *
7 | * Permission is hereby granted, free of charge, to any person obtaining a copy
8 | * of this software and associated documentation files (the "Software"), to deal
9 | * in the Software without restriction, including without limitation the rights
10 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 | * copies of the Software, and to permit persons to whom the Software is
12 | * furnished to do so, subject to the following conditions:
13 | *
14 | * The above copyright notice and this permission notice shall be included in
15 | * all copies or substantial portions of the Software.
16 | *
17 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23 | * THE SOFTWARE.
24 | */
25 |
26 | package org.mockito.kotlin
27 |
28 | import org.mockito.Mockito
29 |
30 | /**
31 | * Creates a spy of the real object.
32 | * The spy calls real methods unless they are stubbed.
33 | */
34 | inline fun spy(): T {
35 | return Mockito.spy(T::class.java)!!
36 | }
37 |
38 | /**
39 | * Creates a spy of the real object, allowing for immediate stubbing.
40 | * The spy calls real methods unless they are stubbed.
41 | */
42 | inline fun spy(stubbing: KStubbing.(T) -> Unit): T {
43 | return Mockito.spy(T::class.java)
44 | .apply { KStubbing(this).stubbing(this) }!!
45 | }
46 |
47 | /**
48 | * Creates a spy of the real object. The spy calls real methods unless they are stubbed.
49 | */
50 | fun spy(value: T): T {
51 | return Mockito.spy(value)!!
52 | }
53 |
54 | /**
55 | * Creates a spy of the real object, allowing for immediate stubbing.
56 | * The spy calls real methods unless they are stubbed.
57 | */
58 | inline fun spy(value: T, stubbing: KStubbing.(T) -> Unit): T {
59 | return spy(value)
60 | .apply { KStubbing(this).stubbing(this) }
61 | }
62 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Mockito-Kotlin
2 |
3 | [  ](https://maven-badges.herokuapp.com/maven-central/org.mockito.kotlin/mockito-kotlin)
4 | [](https://s01.oss.sonatype.org/content/repositories/snapshots/org/mockito/kotlin/mockito-kotlin/)
5 |
6 | A small library that provides helper functions to work with [Mockito](https://github.com/mockito/mockito) in Kotlin.
7 |
8 | ## Install
9 |
10 | Mockito-Kotlin is available on Maven Central.
11 | For Gradle users, add the following to your `build.gradle`, replacing `x.x.x` with the latest version:
12 |
13 | ```groovy
14 | testImplementation "org.mockito.kotlin:mockito-kotlin:x.x.x"
15 | ```
16 |
17 | ## Example
18 |
19 | A test using Mockito-Kotlin typically looks like the following:
20 |
21 | ```kotlin
22 | @Test
23 | fun doAction_doesSomething(){
24 | /* Given */
25 | val mock = mock {
26 | on { getText() } doReturn "text"
27 | }
28 | val classUnderTest = ClassUnderTest(mock)
29 |
30 | /* When */
31 | classUnderTest.doAction()
32 |
33 | /* Then */
34 | verify(mock).doSomething(any())
35 | }
36 | ```
37 |
38 | For more info and samples, see the [Wiki](https://github.com/mockito/mockito-kotlin/wiki).
39 |
40 | ## Building
41 |
42 | Mockito-Kotlin is built with Gradle.
43 |
44 | - `./gradlew build` builds and tests the project
45 | - `./gradlew publishToMavenLocal` installs the maven artifacts in your local repository
46 | - `./gradlew check` runs the test suite (See Testing below)
47 |
48 | ### Versioning
49 |
50 | Mockito-Kotlin roughly follows SEMVER
51 |
52 | ### Testing
53 |
54 | Mockito-Kotlin's test suite is located in a separate `tests` module,
55 | to allow running the tests using several Kotlin versions whilst still
56 | keeping the base module at a recent version.
57 |
58 | - `./gradlew check` runs the checks including tests.
59 |
60 | Usually it is enough to test only using the default Kotlin versions;
61 | CI will test against multiple versions.
62 | If you want to test using a different Kotlin version locally,
63 | add the `-PtestKotlinVersion=1.2.3` argument to the Gradle invocation while running the tests.
64 |
65 | ### Acknowledgements
66 |
67 | `mockito-kotlin` was created and developed by [nhaarman@](https://github.com/nhaarman) after which the repository was integrated into the official Mockito GitHub organization.
68 | We would like to thank Niek for the original idea and extensive work plus support that went into `mockito-kotlin`.
69 |
--------------------------------------------------------------------------------
/mockito-kotlin/src/main/kotlin/org/mockito/kotlin/Stubber.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * The MIT License
3 | *
4 | * Copyright (c) 2018 Niek Haarman
5 | * Copyright (c) 2007 Mockito contributors
6 | *
7 | * Permission is hereby granted, free of charge, to any person obtaining a copy
8 | * of this software and associated documentation files (the "Software"), to deal
9 | * in the Software without restriction, including without limitation the rights
10 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 | * copies of the Software, and to permit persons to whom the Software is
12 | * furnished to do so, subject to the following conditions:
13 | *
14 | * The above copyright notice and this permission notice shall be included in
15 | * all copies or substantial portions of the Software.
16 | *
17 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23 | * THE SOFTWARE.
24 | */
25 |
26 | package org.mockito.kotlin
27 |
28 | import kotlinx.coroutines.runBlocking
29 | import org.mockito.Mockito
30 | import org.mockito.invocation.InvocationOnMock
31 | import org.mockito.stubbing.Stubber
32 | import kotlin.reflect.KClass
33 |
34 | fun doAnswer(answer: (InvocationOnMock) -> T?): Stubber {
35 | return Mockito.doAnswer { answer(it) }!!
36 | }
37 |
38 | fun doCallRealMethod(): Stubber {
39 | return Mockito.doCallRealMethod()!!
40 | }
41 |
42 | fun doNothing(): Stubber {
43 | return Mockito.doNothing()!!
44 | }
45 |
46 | fun doReturn(value: Any?): Stubber {
47 | return Mockito.doReturn(value)!!
48 | }
49 |
50 | fun doReturn(toBeReturned: Any?, vararg toBeReturnedNext: Any?): Stubber {
51 | return Mockito.doReturn(
52 | toBeReturned,
53 | *toBeReturnedNext
54 | )!!
55 | }
56 |
57 | fun doThrow(toBeThrown: KClass): Stubber {
58 | return Mockito.doThrow(toBeThrown.java)!!
59 | }
60 |
61 | fun doThrow(vararg toBeThrown: Throwable): Stubber {
62 | return Mockito.doThrow(*toBeThrown)!!
63 | }
64 |
65 | fun Stubber.whenever(mock: T) = `when`(mock)
66 |
67 | /**
68 | * Alias for when with suspending function
69 | *
70 | * Warning: Only one method call can be stubbed in the function.
71 | * Subsequent method calls are ignored!
72 | */
73 | fun Stubber.wheneverBlocking(mock: T, f: suspend T.() -> Unit) {
74 | val m = whenever(mock)
75 | runBlocking { m.f() }
76 | }
77 |
--------------------------------------------------------------------------------
/tests/src/test/kotlin/test/VerificationTest.kt:
--------------------------------------------------------------------------------
1 | package test
2 |
3 | import com.nhaarman.expect.expect
4 | import org.junit.Test
5 | import org.mockito.exceptions.base.MockitoAssertionError
6 | import org.mockito.kotlin.*
7 | import org.mockito.kotlin.verify
8 |
9 | class VerificationTest : TestBase() {
10 |
11 | @Test
12 | fun atLeastXInvocations() {
13 | mock().apply {
14 | string("")
15 | string("")
16 |
17 | verify(this, atLeast(2)).string(any())
18 | }
19 | }
20 |
21 | @Test
22 | fun testAtLeastOnce() {
23 | mock().apply {
24 | string("")
25 | string("")
26 |
27 | verify(this, atLeastOnce()).string(any())
28 | }
29 | }
30 |
31 | @Test
32 | fun atMostXInvocations() {
33 | mock().apply {
34 | string("")
35 | string("")
36 |
37 | verify(this, atMost(2)).string(any())
38 | }
39 | }
40 |
41 | @Test
42 | fun testCalls() {
43 | mock().apply {
44 | string("")
45 | string("")
46 |
47 | inOrder(this).verify(this, calls(2)).string(any())
48 | }
49 | }
50 |
51 | @Test
52 | fun testInOrderWithLambda() {
53 | /* Given */
54 | val a = mock<() -> Unit>()
55 | val b = mock<() -> Unit>()
56 |
57 | /* When */
58 | b()
59 | a()
60 |
61 | /* Then */
62 | inOrder(a, b) {
63 | verify(b).invoke()
64 | verify(a).invoke()
65 | }
66 | }
67 |
68 | @Test
69 | fun testInOrderWithReceiver() {
70 | /* Given */
71 | val mock = mock()
72 |
73 | /* When */
74 | mock.string("")
75 | mock.int(0)
76 |
77 | /* Then */
78 | mock.inOrder {
79 | verify().string(any())
80 | verify().int(any())
81 | verifyNoMoreInteractions()
82 | }
83 | }
84 |
85 | @Test
86 | fun testClearInvocations() {
87 | val mock = mock().apply {
88 | string("")
89 | }
90 |
91 | clearInvocations(mock)
92 |
93 | verify(mock, never()).string(any())
94 | }
95 |
96 | @Test
97 | fun testDescription() {
98 | try {
99 | mock().apply {
100 | verify(this, description("Test")).string(any())
101 | }
102 | throw AssertionError("Verify should throw Exception.")
103 | } catch (e: MockitoAssertionError) {
104 | expect(e.message).toContain("Test")
105 | }
106 | }
107 |
108 | @Test
109 | fun testAfter() {
110 | mock().apply {
111 | int(3)
112 | verify(this, after(10)).int(3)
113 | }
114 | }
115 | }
116 |
--------------------------------------------------------------------------------
/tests/src/test/kotlin/test/AdditionalMatchersTest.kt:
--------------------------------------------------------------------------------
1 | package test
2 |
3 | import org.junit.Test
4 | import org.mockito.kotlin.*
5 |
6 | class AdditionalCaptorsTest : TestBase() {
7 |
8 | @Test
9 | fun testGeq() {
10 | mock().apply {
11 | int(1)
12 | verify(this).int(geq(0))
13 | verify(this).int(geq(1))
14 | verify(this, never()).int(geq(2))
15 | }
16 | }
17 |
18 | @Test
19 | fun testLeq() {
20 | mock().apply {
21 | int(1)
22 | verify(this).int(leq(2))
23 | verify(this).int(leq(1))
24 | verify(this, never()).int(leq(0))
25 | }
26 | }
27 |
28 | @Test
29 | fun testGt() {
30 | mock().apply {
31 | int(1)
32 | verify(this).int(gt(0))
33 | verify(this, never()).int(gt(1))
34 | }
35 | }
36 |
37 | @Test
38 | fun testLt() {
39 | mock().apply {
40 | int(1)
41 | verify(this).int(lt(2))
42 | verify(this, never()).int(lt(1))
43 | }
44 | }
45 |
46 | @Test
47 | fun testCmpEq() {
48 | mock().apply {
49 | int(1)
50 | verify(this).int(cmpEq(1))
51 | verify(this, never()).int(cmpEq(2))
52 | }
53 | }
54 |
55 | @Test
56 | fun testAryEqPrimitive() {
57 | mock().apply {
58 | intArray(intArrayOf(1, 2, 3))
59 | verify(this).intArray(aryEq(intArrayOf(1, 2, 3)))
60 | verify(this, never()).intArray(aryEq(intArrayOf(1, 2)))
61 | }
62 | }
63 |
64 | @Test
65 | fun testAryEq() {
66 | mock().apply {
67 | stringArray(arrayOf("Hello", "there"))
68 | verify(this).stringArray(aryEq(arrayOf("Hello", "there")))
69 | verify(this, never()).stringArray(aryEq(arrayOf("Hello")))
70 | }
71 | }
72 |
73 | @Test
74 | fun testfind() {
75 | mock().apply {
76 | string("Hello")
77 | verify(this).string(find("l+o$".toRegex()))
78 | verify(this, never()).string(find("l$".toRegex()))
79 | }
80 | }
81 |
82 | @Test
83 | fun testAnd() {
84 | mock().apply {
85 | int(5)
86 | verify(this).int(and(geq(4), leq(6)))
87 | verify(this, never()).int(and(geq(4), leq(4)))
88 | }
89 | }
90 |
91 | @Test
92 | fun testOr() {
93 | mock().apply {
94 | int(5)
95 | verify(this).int(and(gt(4), lt(6)))
96 | verify(this, never()).int(and(gt(4), lt(4)))
97 | }
98 | }
99 |
100 | @Test
101 | fun testNot() {
102 | mock().apply {
103 | int(5)
104 | verify(this).int(not(eq(4)))
105 | verify(this, never()).int(not(eq(5)))
106 | }
107 | }
108 | }
109 |
--------------------------------------------------------------------------------
/tests/src/test/kotlin/test/StubberTest.kt:
--------------------------------------------------------------------------------
1 | package test
2 |
3 | import com.nhaarman.expect.expect
4 | import com.nhaarman.expect.expectErrorWithMessage
5 | import org.junit.Test
6 | import org.mockito.kotlin.*
7 |
8 | class StubberTest : TestBase() {
9 |
10 | @Test
11 | fun testDoAnswer() {
12 | val mock = mock()
13 |
14 | doAnswer { "Test" }
15 | .whenever(mock)
16 | .stringResult()
17 |
18 | expect(mock.stringResult()).toBe("Test")
19 | }
20 |
21 | @Test
22 | fun testDoCallRealMethod() {
23 | val mock = mock()
24 |
25 | doReturn("Test").whenever(mock).stringResult()
26 | doCallRealMethod().whenever(mock).stringResult()
27 |
28 | expect(mock.stringResult()).toBe("Default")
29 | }
30 |
31 | @Test
32 | fun testDoNothing() {
33 | val spy = spy(Open())
34 | val array = intArrayOf(3)
35 |
36 | doNothing().whenever(spy).modifiesContents(array)
37 | spy.modifiesContents(array)
38 |
39 | expect(array[0]).toBe(3)
40 | }
41 |
42 | @Test
43 | fun testDoReturnValue() {
44 | val mock = mock()
45 |
46 | doReturn("test").whenever(mock).stringResult()
47 |
48 | expect(mock.stringResult()).toBe("test")
49 | }
50 |
51 | @Test
52 | fun testDoReturnNullValue() {
53 | val mock = mock()
54 |
55 | doReturn(null).whenever(mock).stringResult()
56 |
57 | expect(mock.stringResult()).toBeNull()
58 | }
59 |
60 | @Test
61 | fun testDoReturnNullValues() {
62 | val mock = mock()
63 |
64 | doReturn(null, null).whenever(mock).stringResult()
65 |
66 | expect(mock.stringResult()).toBeNull()
67 | expect(mock.stringResult()).toBeNull()
68 | }
69 |
70 | @Test
71 | fun testDoReturnValues() {
72 | val mock = mock()
73 |
74 | doReturn("test", "test2").whenever(mock).stringResult()
75 |
76 | expect(mock.stringResult()).toBe("test")
77 | expect(mock.stringResult()).toBe("test2")
78 | }
79 |
80 | @Test
81 | fun testDoThrowClass() {
82 | val mock = mock()
83 |
84 | doThrow(IllegalStateException::class).whenever(mock).go()
85 |
86 | try {
87 | mock.go()
88 | throw AssertionError("Call should have thrown.")
89 | } catch (e: IllegalStateException) {
90 | }
91 | }
92 |
93 | @Test
94 | fun testDoThrow() {
95 | val mock = mock()
96 |
97 | doThrow(IllegalStateException("test")).whenever(mock).go()
98 |
99 | expectErrorWithMessage("test").on {
100 | mock.go()
101 | }
102 | }
103 |
104 | @Test
105 | fun testStubberOnBlockExtension() {
106 | val mock = mock {
107 | doReturn("Test").on { stringResult() }
108 | }
109 |
110 | expect(mock.stringResult()).toBe("Test")
111 | }
112 | }
113 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%" == "" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%" == "" set DIRNAME=.
29 | set APP_BASE_NAME=%~n0
30 | set APP_HOME=%DIRNAME%
31 |
32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
34 |
35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
37 |
38 | @rem Find java.exe
39 | if defined JAVA_HOME goto findJavaFromJavaHome
40 |
41 | set JAVA_EXE=java.exe
42 | %JAVA_EXE% -version >NUL 2>&1
43 | if "%ERRORLEVEL%" == "0" goto execute
44 |
45 | echo.
46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
47 | echo.
48 | echo Please set the JAVA_HOME variable in your environment to match the
49 | echo location of your Java installation.
50 |
51 | goto fail
52 |
53 | :findJavaFromJavaHome
54 | set JAVA_HOME=%JAVA_HOME:"=%
55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
56 |
57 | if exist "%JAVA_EXE%" goto execute
58 |
59 | echo.
60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
61 | echo.
62 | echo Please set the JAVA_HOME variable in your environment to match the
63 | echo location of your Java installation.
64 |
65 | goto fail
66 |
67 | :execute
68 | @rem Setup the command line
69 |
70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
71 |
72 |
73 | @rem Execute Gradle
74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
75 |
76 | :end
77 | @rem End local scope for the variables with windows NT shell
78 | if "%ERRORLEVEL%"=="0" goto mainEnd
79 |
80 | :fail
81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
82 | rem the _cmd.exe /c_ return code!
83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
84 | exit /b 1
85 |
86 | :mainEnd
87 | if "%OS%"=="Windows_NT" endlocal
88 |
89 | :omega
90 |
--------------------------------------------------------------------------------
/tests/src/test/kotlin/test/EqTest.kt:
--------------------------------------------------------------------------------
1 | package test
2 |
3 | /*
4 | * The MIT License
5 | *
6 | * Copyright (c) 2016 Niek Haarman
7 | * Copyright (c) 2007 Mockito contributors
8 | *
9 | * Permission is hereby granted, free of charge, to any person obtaining a copy
10 | * of this software and associated documentation files (the "Software"), to deal
11 | * in the Software without restriction, including without limitation the rights
12 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13 | * copies of the Software, and to permit persons to whom the Software is
14 | * furnished to do so, subject to the following conditions:
15 | *
16 | * The above copyright notice and this permission notice shall be included in
17 | * all copies or substantial portions of the Software.
18 | *
19 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 | * THE SOFTWARE.
26 | */
27 |
28 | import com.nhaarman.expect.expect
29 | import org.mockito.kotlin.eq
30 | import org.mockito.kotlin.mock
31 | import org.junit.After
32 | import org.junit.Before
33 | import org.junit.Test
34 | import org.mockito.Mockito
35 |
36 | class EqTest : TestBase() {
37 |
38 | private val interfaceInstance: MyInterface = MyClass()
39 | private val openClassInstance: MyClass = MyClass()
40 | private val closedClassInstance: ClosedClass = ClosedClass()
41 |
42 | private lateinit var doAnswer: Open
43 |
44 | @Before
45 | fun setup() {
46 | /* Create a proper Mockito state */
47 | doAnswer = Mockito.doAnswer { }.`when`(mock())
48 | }
49 |
50 | @After
51 | override fun tearDown() {
52 | super.tearDown()
53 |
54 | /* Close `any` Mockito state */
55 | doAnswer.go(0)
56 | }
57 |
58 | @Test
59 | fun eqInterfaceInstance() {
60 | /* When */
61 | val result = eq(interfaceInstance)
62 |
63 | /* Then */
64 | expect(result).toNotBeNull()
65 | }
66 |
67 | @Test
68 | fun eqOpenClassInstance() {
69 | /* When */
70 | val result = eq(openClassInstance)
71 |
72 | /* Then */
73 | expect(result).toNotBeNull()
74 | }
75 |
76 | @Test
77 | fun eqClosedClassInstance() {
78 | /* When */
79 | val result = eq(closedClassInstance)
80 |
81 | /* Then */
82 | expect(result).toNotBeNull()
83 | }
84 |
85 | @Test
86 | fun nullArgument() {
87 | /* Given */
88 | val s: String? = null
89 |
90 | /* When */
91 | val result = eq(s)
92 |
93 | /* Then */
94 | expect(result).toBeNull()
95 | }
96 |
97 | private interface MyInterface
98 | private open class MyClass : MyInterface
99 | class ClosedClass
100 | }
101 |
102 |
--------------------------------------------------------------------------------
/.github/workflows/ci.yml:
--------------------------------------------------------------------------------
1 | #
2 | # CI build that assembles artifacts and runs tests.
3 | # If validation is successful this workflow releases from the main dev branch.
4 | #
5 | # - skipping CI: add [skip ci] to the commit message
6 | # - skipping release: add [skip release] to the commit message
7 | #
8 | name: CI
9 |
10 | on:
11 | push:
12 | branches:
13 | - main
14 | tags:
15 | - 5.*
16 | pull_request:
17 | branches:
18 | - main
19 |
20 | jobs:
21 |
22 | #
23 | # SINGLE-JOB
24 | #
25 | verify:
26 | runs-on: ubuntu-latest
27 | if: "! contains(toJSON(github.event.commits.*.message), '[skip ci]')"
28 |
29 | steps:
30 |
31 | - name: 1. Check out code
32 | uses: actions/checkout@v2 # https://github.com/actions/checkout
33 |
34 | - name: 2. Set up Java 11
35 | uses: actions/setup-java@v1 # https://github.com/actions/setup-java
36 | with:
37 | java-version: 11
38 |
39 | - name: 3. Validate Gradle wrapper
40 | uses: gradle/wrapper-validation-action@v1 # https://github.com/gradle/wrapper-validation-action
41 |
42 | #
43 | # Main build job
44 | #
45 | build:
46 | needs: [verify]
47 | runs-on: ubuntu-latest
48 |
49 | # Definition of the build matrix
50 | strategy:
51 | matrix:
52 | mock-maker: ['mock-maker-default', 'mock-maker-inline']
53 | kotlin: ['1.9.20']
54 | # Note that the old Travis CI referenced other Kotlin versions: '1.0.7', '1.1.61', '1.2.50'
55 | # However, those versions of Kotlin don't work with latest Gradle
56 |
57 | steps:
58 |
59 | - name: 1. Check out code
60 | uses: actions/checkout@v2 # https://github.com/actions/checkout
61 |
62 | - name: 2. Set up Java 11
63 | uses: actions/setup-java@v1 # https://github.com/actions/setup-java
64 | with:
65 | java-version: 11
66 |
67 | - name: 3. Build with Kotlin ${{ matrix.kotlin }} and mock-maker ${{ matrix.mock-maker }}
68 | run: |
69 | ops/mockMakerInline.sh
70 | ./gradlew build -PtestKotlinVersion=${{ matrix.kotlin }}
71 | env:
72 | MOCK_MAKER: ${{ matrix.mock-maker }}
73 |
74 | #
75 | # Release job, only for pushes to the main development branch
76 | #
77 | release:
78 | runs-on: ubuntu-latest
79 | needs: [build] # build job must pass before we can release
80 |
81 | if: github.event_name == 'push'
82 | && (github.ref == 'refs/heads/main' || startsWith(github.ref, 'refs/tags/5.'))
83 | && github.repository == 'mockito/mockito-kotlin'
84 | && !contains(toJSON(github.event.commits.*.message), '[skip release]')
85 |
86 | steps:
87 |
88 | - name: Check out code
89 | uses: actions/checkout@v2 # https://github.com/actions/checkout
90 | with:
91 | fetch-depth: '0' # https://github.com/shipkit/shipkit-changelog#fetch-depth-on-ci
92 |
93 | - name: Set up Java 11
94 | uses: actions/setup-java@v1
95 | with:
96 | java-version: 11
97 |
98 | - name: Build and release
99 | run: ./gradlew githubRelease publishToSonatype closeAndReleaseStagingRepository releaseSummary
100 | env:
101 | GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}}
102 | NEXUS_TOKEN_USER: ${{secrets.NEXUS_TOKEN_USER}}
103 | NEXUS_TOKEN_PWD: ${{secrets.NEXUS_TOKEN_PWD}}
104 | PGP_KEY: ${{secrets.PGP_KEY}}
105 | PGP_PWD: ${{secrets.PGP_PWD}}
106 |
--------------------------------------------------------------------------------
/mockito-kotlin/src/test/kotlin/org/mockito/kotlin/BDDMockitoKtTest.kt:
--------------------------------------------------------------------------------
1 | package org.mockito.kotlin
2 |
3 | import kotlinx.coroutines.Dispatchers
4 | import kotlinx.coroutines.runBlocking
5 | import kotlinx.coroutines.withContext
6 | import org.junit.Assert.assertEquals
7 | import org.junit.Test
8 | import kotlin.test.assertFailsWith
9 |
10 | class BDDMockitoKtTest {
11 |
12 | @Test
13 | fun willSuspendableAnswer_withoutArgument() = runBlocking {
14 | val fixture: SomeInterface = mock()
15 |
16 | given(fixture.suspending()).willSuspendableAnswer {
17 | withContext(Dispatchers.Default) { 42 }
18 | }
19 |
20 | assertEquals(42, fixture.suspending())
21 | then(fixture).should().suspending()
22 | Unit
23 | }
24 |
25 | @Test
26 | fun willSuspendableAnswer_withArgument() = runBlocking {
27 | val fixture: SomeInterface = mock()
28 |
29 | given(fixture.suspendingWithArg(any())).willSuspendableAnswer {
30 | withContext(Dispatchers.Default) { it.getArgument(0) }
31 | }
32 |
33 | assertEquals(42, fixture.suspendingWithArg(42))
34 | then(fixture).should().suspendingWithArg(42)
35 | Unit
36 | }
37 |
38 | @Test
39 | fun willSuspendableAnswer_givenBlocking() {
40 | val fixture: SomeInterface = mock()
41 |
42 | givenBlocking { fixture.suspending() }.willSuspendableAnswer {
43 | withContext(Dispatchers.Default) { 42 }
44 | }
45 |
46 | val result = runBlocking {
47 | fixture.suspending()
48 | }
49 |
50 | assertEquals(42, result)
51 | then(fixture).shouldBlocking { suspending() }
52 | Unit
53 | }
54 |
55 | @Test
56 | fun willSuspendableAnswer_givenBlocking_withArgument() {
57 | val fixture: SomeInterface = mock()
58 |
59 | givenBlocking { fixture.suspendingWithArg(any()) }.willSuspendableAnswer {
60 | withContext(Dispatchers.Default) { it.getArgument(0) }
61 | }
62 |
63 | val result = runBlocking {
64 | fixture.suspendingWithArg(42)
65 | }
66 |
67 | assertEquals(42, result)
68 | then(fixture).shouldBlocking { suspendingWithArg(42) }
69 | Unit
70 | }
71 |
72 | @Test
73 | fun willThrow_kclass_single() {
74 | val fixture: SomeInterface = mock()
75 |
76 | given(fixture.foo()).willThrow(RuntimeException::class)
77 |
78 | assertFailsWith(RuntimeException::class) {
79 | fixture.foo()
80 | }
81 | }
82 |
83 | @Test
84 | fun willThrow_kclass_multiple() {
85 | val fixture: SomeInterface = mock()
86 |
87 | given(fixture.foo()).willThrow(RuntimeException::class, IllegalArgumentException::class)
88 |
89 | assertFailsWith(RuntimeException::class) {
90 | fixture.foo()
91 | }
92 | assertFailsWith(IllegalArgumentException::class) {
93 | fixture.foo()
94 | }
95 | }
96 |
97 | @Test
98 | fun willReturnConsecutively() {
99 | val fixture: SomeInterface = mock()
100 |
101 | given(fixture.foo()).willReturnConsecutively(listOf(42, 24))
102 |
103 | assertEquals(42, fixture.foo())
104 | assertEquals(24, fixture.foo())
105 | }
106 | }
107 |
108 | interface SomeInterface {
109 | fun foo(): Int
110 |
111 | suspend fun suspending(): Int
112 | suspend fun suspendingWithArg(arg: Int): Int
113 | }
114 |
--------------------------------------------------------------------------------
/tests/src/test/kotlin/test/Classes.kt:
--------------------------------------------------------------------------------
1 | package test
2 |
3 | /*
4 | * The MIT License
5 | *
6 | * Copyright (c) 2016 Niek Haarman
7 | * Copyright (c) 2007 Mockito contributors
8 | *
9 | * Permission is hereby granted, free of charge, to any person obtaining a copy
10 | * of this software and associated documentation files (the "Software"), to deal
11 | * in the Software without restriction, including without limitation the rights
12 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13 | * copies of the Software, and to permit persons to whom the Software is
14 | * furnished to do so, subject to the following conditions:
15 | *
16 | * The above copyright notice and this permission notice shall be included in
17 | * all copies or substantial portions of the Software.
18 | *
19 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 | * THE SOFTWARE.
26 | */
27 |
28 | open class Open {
29 | open fun go(vararg arg: Any?) {
30 | }
31 |
32 | open fun modifiesContents(a: IntArray) {
33 | for (i in 0..a.size - 1) {
34 | a[i] = a[i] + 1
35 | }
36 | }
37 |
38 | open fun stringResult() = "Default"
39 |
40 | fun throwsNPE(): Any = throw NullPointerException("Test")
41 | }
42 |
43 | class Closed
44 |
45 | interface Methods {
46 |
47 | fun intArray(i: IntArray)
48 | fun closed(c: Closed)
49 | fun closedArray(a: Array)
50 | fun closedNullableArray(a: Array)
51 | fun closedCollection(c: Collection)
52 | fun closedList(c: List)
53 | fun closedStringMap(m: Map)
54 | fun closedSet(s: Set)
55 | fun string(s: String)
56 | fun boolean(b: Boolean)
57 | fun byte(b: Byte)
58 | fun char(c: Char)
59 | fun short(s: Short)
60 | fun int(i: Int)
61 | fun long(l: Long)
62 | fun float(f: Float)
63 | fun double(d: Double)
64 | fun closedVararg(vararg c: Closed)
65 | fun throwableClass(t: ThrowableClass)
66 | fun nullableString(s: String?)
67 |
68 | fun stringResult(): String
69 | fun stringResult(s: String): String
70 | fun nullableStringResult(): String?
71 | fun builderMethod(): Methods
72 | fun varargBooleanResult(vararg values: String): Boolean
73 | fun stringArray(a: Array)
74 | fun argAndVararg(s: String, vararg a: String)
75 |
76 | fun nonDefaultReturnType(): ExtraInterface
77 | }
78 |
79 | interface ExtraInterface
80 |
81 | abstract class ThrowingConstructor {
82 |
83 | constructor() {
84 | error("Error in constructor")
85 | }
86 | }
87 |
88 | abstract class ThrowingConstructorWithArgument {
89 |
90 | constructor(s: String) {
91 | error("Error in constructor: $s")
92 | }
93 | }
94 |
95 | abstract class NonThrowingConstructorWithArgument {
96 |
97 | constructor() {
98 | error("Error in constructor")
99 | }
100 |
101 | @Suppress("UNUSED_PARAMETER")
102 | constructor(s: String)
103 | }
104 |
105 | interface GenericMethods {
106 | fun genericMethod(): T
107 | fun nullableReturnType(): T?
108 | }
109 |
110 | class ThrowableClass(cause: Throwable) : Throwable(cause)
111 |
--------------------------------------------------------------------------------
/tests/src/test/kotlin/test/BDDMockitoTest.kt:
--------------------------------------------------------------------------------
1 | package test
2 |
3 | import com.nhaarman.expect.expect
4 | import org.junit.Test
5 | import org.mockito.kotlin.*
6 | import org.mockito.stubbing.Answer
7 |
8 | class BDDMockitoTest {
9 |
10 | @Test
11 | fun given_will_properlyStubs() {
12 | /* Given */
13 | val mock = mock()
14 |
15 | /* When */
16 | given(mock.stringResult()) will Answer { "Test" }
17 |
18 | /* Then */
19 | expect(mock.stringResult()).toBe("Test")
20 | }
21 |
22 | @Test
23 | fun given_willReturn_properlyStubs() {
24 | /* Given */
25 | val mock = mock()
26 |
27 | /* When */
28 | given(mock.stringResult()).willReturn("Test")
29 |
30 | /* Then */
31 | expect(mock.stringResult()).toBe("Test")
32 | }
33 |
34 | @Test
35 | fun givenLambda_willReturn_properlyStubs() {
36 | /* Given */
37 | val mock = mock()
38 |
39 | /* When */
40 | given { mock.stringResult() }.willReturn("Test")
41 |
42 | /* Then */
43 | expect(mock.stringResult()).toBe("Test")
44 | }
45 |
46 | @Test
47 | fun given_willReturnLambda_properlyStubs() {
48 | /* Given */
49 | val mock = mock()
50 |
51 | /* When */
52 | given(mock.stringResult()).willReturn { "Test" }
53 |
54 | /* Then */
55 | expect(mock.stringResult()).toBe("Test")
56 | }
57 |
58 | @Test
59 | fun givenLambda_willReturnLambda_properlyStubs() {
60 | /* Given */
61 | val mock = mock()
62 |
63 | /* When */
64 | given { mock.stringResult() } willReturn { "Test" }
65 |
66 | /* Then */
67 | expect(mock.stringResult()).toBe("Test")
68 | }
69 |
70 | @Test
71 | fun given_willAnswer_properlyStubs() {
72 | /* Given */
73 | val mock = mock()
74 |
75 | /* When */
76 | given(mock.stringResult()).willAnswer { "Test" }
77 |
78 | /* Then */
79 | expect(mock.stringResult()).toBe("Test")
80 | }
81 |
82 | @Test
83 | fun given_willAnswerInfix_properlyStubs() {
84 | /* Given */
85 | val mock = mock()
86 |
87 | /* When */
88 | given(mock.stringResult()) willAnswer { "Test" }
89 |
90 | /* Then */
91 | expect(mock.stringResult()).toBe("Test")
92 | }
93 |
94 | @Test
95 | fun given_willAnswerInfix_withInvocationInfo_properlyStubs() {
96 | /* Given */
97 | val mock = mock()
98 |
99 | /* When */
100 | given(mock.stringResult(any())) willAnswer { invocation ->
101 | (invocation.arguments[0] as String)
102 | .reversed()
103 | }
104 |
105 | /* Then */
106 | expect(mock.stringResult("Test")).toBe("tseT")
107 | }
108 |
109 | @Test(expected = IllegalStateException::class)
110 | fun given_willThrowInfix_properlyStubs() {
111 | /* Given */
112 | val mock = mock()
113 |
114 | /* When */
115 | given(mock.stringResult()) willThrow { IllegalStateException() }
116 | mock.stringResult()
117 | }
118 |
119 | @Test
120 | fun then() {
121 | /* Given */
122 | val mock = mock()
123 | whenever(mock.stringResult()).thenReturn("Test")
124 |
125 | /* When */
126 | mock.stringResult()
127 |
128 | /* Then */
129 | org.mockito.kotlin.then(mock).should().stringResult()
130 | }
131 | }
132 |
--------------------------------------------------------------------------------
/tests/src/test/kotlin/test/inline/UsingMockMakerInlineTest.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * The MIT License
3 | *
4 | * Copyright (c) 2016 Ian J. De Silva
5 | *
6 | * Permission is hereby granted, free of charge, to any person obtaining a copy
7 | * of this software and associated documentation files (the "Software"), to deal
8 | * in the Software without restriction, including without limitation the rights
9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 | * copies of the Software, and to permit persons to whom the Software is
11 | * furnished to do so, subject to the following conditions:
12 | *
13 | * The above copyright notice and this permission notice shall be included in
14 | * all copies or substantial portions of the Software.
15 | *
16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 | * THE SOFTWARE.
23 | */
24 |
25 | import com.nhaarman.expect.expect
26 | import org.junit.Assume.assumeTrue
27 | import org.junit.Before
28 | import org.junit.Test
29 | import org.mockito.kotlin.*
30 | import test.mockMakerInlineEnabled
31 | import java.io.IOException
32 | import java.math.BigInteger
33 |
34 | class UsingMockMakerInlineTest {
35 |
36 | class ClassToBeMocked {
37 |
38 | fun doSomething(@Suppress("UNUSED_PARAMETER") c: ClassToBeMocked) {
39 | }
40 |
41 | fun doSomethingElse(value: BigInteger): BigInteger {
42 | return value.plus(BigInteger.ONE)
43 | }
44 | }
45 |
46 | @Before
47 | fun setup() {
48 | mockMakerInlineEnabled = null
49 | assumeTrue(mockMakerInlineEnabled())
50 | }
51 |
52 | @Test
53 | fun mockClosedClass() {
54 | /* When */
55 | val result = mock()
56 |
57 | /* Then */
58 | expect(result).toNotBeNull()
59 | }
60 |
61 | @Test
62 | fun anyClosedClass() {
63 | /* Given */
64 | val mock = mock()
65 |
66 | /* When */
67 | mock.doSomething(mock)
68 |
69 | /* Then */
70 | verify(mock).doSomething(any())
71 | }
72 |
73 | @Test
74 | fun mockClosedFunction_mockStubbing() {
75 | /* Given */
76 | val mock = mock {
77 | on { doSomethingElse(any()) } doReturn (BigInteger.ONE)
78 | }
79 |
80 | /* When */
81 | val result = mock.doSomethingElse(BigInteger.TEN)
82 |
83 | /* Then */
84 | expect(result).toBe(BigInteger.ONE)
85 | }
86 |
87 | @Test
88 | fun mockClosedFunction_whenever() {
89 | /* Given */
90 | val mock = mock()
91 | whenever(mock.doSomethingElse(any())).doReturn(BigInteger.ONE)
92 |
93 | /* When */
94 | val result = mock.doSomethingElse(BigInteger.TEN)
95 |
96 | /* Then */
97 | expect(result).toBe(BigInteger.ONE)
98 | }
99 |
100 | /** https://github.com/nhaarman/mockito-kotlin/issues/27 */
101 | @Test
102 | fun anyThrowableWithSingleThrowableConstructor() {
103 | mock().apply {
104 | throwableClass(ThrowableClass(IOException()))
105 | verify(this).throwableClass(any())
106 | }
107 | }
108 |
109 | interface Methods {
110 |
111 | fun throwableClass(t: ThrowableClass)
112 | }
113 |
114 | class ThrowableClass(cause: Throwable) : Throwable(cause)
115 |
116 | }
117 |
--------------------------------------------------------------------------------
/mockito-kotlin/src/main/kotlin/org/mockito/kotlin/KStubbing.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * The MIT License
3 | *
4 | * Copyright (c) 2018 Niek Haarman
5 | * Copyright (c) 2007 Mockito contributors
6 | *
7 | * Permission is hereby granted, free of charge, to any person obtaining a copy
8 | * of this software and associated documentation files (the "Software"), to deal
9 | * in the Software without restriction, including without limitation the rights
10 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 | * copies of the Software, and to permit persons to whom the Software is
12 | * furnished to do so, subject to the following conditions:
13 | *
14 | * The above copyright notice and this permission notice shall be included in
15 | * all copies or substantial portions of the Software.
16 | *
17 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23 | * THE SOFTWARE.
24 | */
25 |
26 | package org.mockito.kotlin
27 |
28 | import org.mockito.kotlin.internal.createInstance
29 | import kotlinx.coroutines.runBlocking
30 | import org.mockito.Mockito
31 | import org.mockito.exceptions.misusing.NotAMockException
32 | import org.mockito.stubbing.OngoingStubbing
33 | import org.mockito.stubbing.Stubber
34 | import kotlin.reflect.KClass
35 |
36 | inline fun stubbing(
37 | mock: T,
38 | stubbing: KStubbing.(T) -> Unit
39 | ) {
40 | KStubbing(mock).stubbing(mock)
41 | }
42 |
43 | inline fun T.stub(stubbing: KStubbing.(T) -> Unit): T {
44 | return apply { KStubbing(this).stubbing(this) }
45 | }
46 |
47 | class KStubbing(val mock: T) {
48 | init {
49 | if (!mockingDetails(mock).isMock) throw NotAMockException("Stubbing target is not a mock!")
50 | }
51 |
52 | fun on(methodCall: R): OngoingStubbing = Mockito.`when`(methodCall)
53 |
54 | fun onGeneric(methodCall: T.() -> R?, c: KClass): OngoingStubbing {
55 | val r = try {
56 | mock.methodCall()
57 | } catch (e: NullPointerException) {
58 | // An NPE may be thrown by the Kotlin type system when the MockMethodInterceptor returns a
59 | // null value for a non-nullable generic type.
60 | // We catch this NPE to return a valid instance.
61 | // The Mockito state has already been modified at this point to reflect
62 | // the wanted changes.
63 | createInstance(c)
64 | }
65 | return Mockito.`when`(r)
66 | }
67 |
68 | inline fun onGeneric(noinline methodCall: T.() -> R?): OngoingStubbing {
69 | return onGeneric(methodCall, R::class)
70 | }
71 |
72 | fun on(methodCall: T.() -> R): OngoingStubbing {
73 | return try {
74 | Mockito.`when`(mock.methodCall())
75 | } catch (e: NullPointerException) {
76 | throw MockitoKotlinException(
77 | "NullPointerException thrown when stubbing.\nThis may be due to two reasons:\n\t- The method you're trying to stub threw an NPE: look at the stack trace below;\n\t- You're trying to stub a generic method: try `onGeneric` instead.",
78 | e
79 | )
80 | }
81 | }
82 |
83 | fun KStubbing.onBlocking(
84 | m: suspend T.() -> R
85 | ): OngoingStubbing {
86 | return runBlocking { Mockito.`when`(mock.m()) }
87 | }
88 |
89 | fun Stubber.on(methodCall: T.() -> Unit) {
90 | this.`when`(mock).methodCall()
91 | }
92 | }
93 |
--------------------------------------------------------------------------------
/tests/src/test/kotlin/test/SpyTest.kt:
--------------------------------------------------------------------------------
1 | package test
2 |
3 | /*
4 | * The MIT License
5 | *
6 | * Copyright (c) 2016 Niek Haarman
7 | * Copyright (c) 2007 Mockito contributors
8 | *
9 | * Permission is hereby granted, free of charge, to any person obtaining a copy
10 | * of this software and associated documentation files (the "Software"), to deal
11 | * in the Software without restriction, including without limitation the rights
12 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13 | * copies of the Software, and to permit persons to whom the Software is
14 | * furnished to do so, subject to the following conditions:
15 | *
16 | * The above copyright notice and this permission notice shall be included in
17 | * all copies or substantial portions of the Software.
18 | *
19 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 | * THE SOFTWARE.
26 | */
27 |
28 | import com.nhaarman.expect.expect
29 | import org.junit.After
30 | import org.junit.Test
31 | import org.mockito.Mockito
32 | import org.mockito.kotlin.*
33 | import java.util.*
34 |
35 | class SpyTest : TestBase() {
36 |
37 | private val interfaceInstance: MyInterface = MyClass()
38 | private val openClassInstance: MyClass = MyClass()
39 | private val closedClassInstance: ClosedClass = ClosedClass()
40 |
41 | @After
42 | override fun tearDown() {
43 | super.tearDown()
44 | Mockito.validateMockitoUsage()
45 | }
46 |
47 | @Test
48 | fun spyInterfaceInstance() {
49 | /* When */
50 | val result = spy(interfaceInstance)
51 |
52 | /* Then */
53 | expect(result).toNotBeNull()
54 | }
55 |
56 | @Test
57 | fun spyOpenClassInstance() {
58 | /* When */
59 | val result = spy(openClassInstance)
60 |
61 | /* Then */
62 | expect(result).toNotBeNull()
63 | }
64 |
65 | @Test
66 | fun doReturnWithSpy() {
67 | val date = spy(Date())
68 | doReturn(123L).whenever(date).time
69 | expect(date.time).toBe(123L)
70 | }
71 |
72 | @Test
73 | fun doNothingWithSpy() {
74 | val date = spy(Date(0))
75 | doNothing().whenever(date).time = 5L
76 | date.time = 5L
77 | expect(date.time).toBe(0L)
78 | }
79 |
80 | @Test(expected = IllegalArgumentException::class)
81 | fun doThrowWithSpy() {
82 | val date = spy(Date(0))
83 | doThrow(IllegalArgumentException()).whenever(date).time
84 | date.time
85 | }
86 |
87 | @Test
88 | fun doCallRealMethodWithSpy() {
89 | val date = spy(Date(0))
90 | doReturn(123L).whenever(date).time
91 | doCallRealMethod().whenever(date).time
92 | expect(date.time).toBe(0L)
93 | }
94 |
95 | @Test
96 | fun doReturnWithDefaultInstanceSpyStubbing() {
97 | val timeVal = 12L
98 |
99 | val dateSpy = spy {
100 | on { time } doReturn timeVal
101 | }
102 |
103 | expect(dateSpy.time).toBe(timeVal)
104 | }
105 |
106 | @Test
107 | fun doReturnWithSpyStubbing() {
108 | val timeVal = 15L
109 |
110 | val dateSpy = spy(Date(0)) {
111 | on { time } doReturn timeVal
112 | }
113 |
114 | expect(dateSpy.time).toBe(timeVal)
115 | }
116 |
117 | @Test
118 | fun passAnyStringToSpy() {
119 | /* Given */
120 | val my = spy(MyClass())
121 |
122 | /* When */
123 | doReturn("mocked").whenever(my).foo(any())
124 |
125 | /* Then */
126 | expect(my.foo("hello")).toBe("mocked")
127 | }
128 |
129 | private interface MyInterface {
130 |
131 | fun foo(value: String): String
132 | }
133 |
134 | private open class MyClass : MyInterface {
135 |
136 | override fun foo(value: String): String = value
137 | }
138 |
139 | private class ClosedClass
140 | }
141 |
142 |
--------------------------------------------------------------------------------
/mockito-kotlin/src/main/kotlin/org/mockito/kotlin/OngoingStubbing.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * The MIT License
3 | *
4 | * Copyright (c) 2018 Niek Haarman
5 | * Copyright (c) 2007 Mockito contributors
6 | *
7 | * Permission is hereby granted, free of charge, to any person obtaining a copy
8 | * of this software and associated documentation files (the "Software"), to deal
9 | * in the Software without restriction, including without limitation the rights
10 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 | * copies of the Software, and to permit persons to whom the Software is
12 | * furnished to do so, subject to the following conditions:
13 | *
14 | * The above copyright notice and this permission notice shall be included in
15 | * all copies or substantial portions of the Software.
16 | *
17 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23 | * THE SOFTWARE.
24 | */
25 |
26 | package org.mockito.kotlin
27 |
28 | import kotlinx.coroutines.CoroutineScope
29 | import kotlinx.coroutines.runBlocking
30 | import org.mockito.Mockito
31 | import org.mockito.invocation.InvocationOnMock
32 | import org.mockito.kotlin.internal.SuspendableAnswer
33 | import org.mockito.stubbing.Answer
34 | import org.mockito.stubbing.OngoingStubbing
35 | import kotlin.reflect.KClass
36 |
37 | /**
38 | * Enables stubbing methods. Use it when you want the mock to return particular value when particular method is called.
39 | *
40 | * Alias for [Mockito.when].
41 | */
42 | @Suppress("NOTHING_TO_INLINE")
43 | inline fun whenever(methodCall: T): OngoingStubbing {
44 | return Mockito.`when`(methodCall)!!
45 | }
46 |
47 | /**
48 | * Enables stubbing suspending methods. Use it when you want the mock to return particular value when particular suspending method is called.
49 | *
50 | * Warning: Only one method call can be stubbed in the function.
51 | * other method calls are ignored!
52 | */
53 | fun wheneverBlocking(methodCall: suspend CoroutineScope.() -> T): OngoingStubbing {
54 | return runBlocking { Mockito.`when`(methodCall()) }
55 | }
56 |
57 | /**
58 | * Sets a return value to be returned when the method is called.
59 | *
60 | * Alias for [OngoingStubbing.thenReturn].
61 | */
62 | infix fun OngoingStubbing.doReturn(t: T): OngoingStubbing {
63 | return thenReturn(t)
64 | }
65 |
66 | /**
67 | * Sets consecutive return values to be returned when the method is called.
68 | *
69 | * Alias for [OngoingStubbing.thenReturn].
70 | */
71 | fun OngoingStubbing.doReturn(t: T, vararg ts: T): OngoingStubbing {
72 | return thenReturn(t, *ts)
73 | }
74 |
75 | /**
76 | * Sets consecutive return values to be returned when the method is called.
77 | */
78 | inline infix fun OngoingStubbing.doReturnConsecutively(ts: List): OngoingStubbing {
79 | return thenReturn(
80 | ts[0],
81 | *ts.drop(1).toTypedArray()
82 | )
83 | }
84 |
85 | /**
86 | * Sets Throwable objects to be thrown when the method is called.
87 | *
88 | * Alias for [OngoingStubbing.thenThrow].
89 | */
90 | infix fun OngoingStubbing.doThrow(t: Throwable): OngoingStubbing {
91 | return thenThrow(t)
92 | }
93 |
94 | /**
95 | * Sets Throwable objects to be thrown when the method is called.
96 | *
97 | * Alias for [OngoingStubbing.doThrow].
98 | */
99 | fun OngoingStubbing.doThrow(
100 | t: Throwable,
101 | vararg ts: Throwable
102 | ): OngoingStubbing {
103 | return thenThrow(t, *ts)
104 | }
105 |
106 | /**
107 | * Sets a Throwable type to be thrown when the method is called.
108 | */
109 | infix fun OngoingStubbing.doThrow(t: KClass): OngoingStubbing {
110 | return thenThrow(t.java)
111 | }
112 |
113 | /**
114 | * Sets Throwable classes to be thrown when the method is called.
115 | */
116 | fun OngoingStubbing.doThrow(
117 | t: KClass,
118 | vararg ts: KClass
119 | ): OngoingStubbing {
120 | return thenThrow(t.java, *ts.map { it.java }.toTypedArray())
121 | }
122 |
123 | /**
124 | * Sets a generic Answer for the method.
125 | *
126 | * Alias for [OngoingStubbing.thenAnswer].
127 | */
128 | infix fun OngoingStubbing.doAnswer(answer: Answer<*>): OngoingStubbing {
129 | return thenAnswer(answer)
130 | }
131 |
132 | /**
133 | * Sets a generic Answer for the method using a lambda.
134 | */
135 | infix fun OngoingStubbing.doAnswer(answer: (InvocationOnMock) -> T?): OngoingStubbing {
136 | return thenAnswer(answer)
137 | }
138 |
139 | infix fun OngoingStubbing.doSuspendableAnswer(answer: suspend (InvocationOnMock) -> T?): OngoingStubbing {
140 | return thenAnswer(SuspendableAnswer(answer))
141 | }
142 |
--------------------------------------------------------------------------------
/mockito-kotlin/src/main/kotlin/org/mockito/kotlin/BDDMockito.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * The MIT License
3 | *
4 | * Copyright (c) 2018 Niek Haarman
5 | * Copyright (c) 2007 Mockito contributors
6 | *
7 | * Permission is hereby granted, free of charge, to any person obtaining a copy
8 | * of this software and associated documentation files (the "Software"), to deal
9 | * in the Software without restriction, including without limitation the rights
10 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 | * copies of the Software, and to permit persons to whom the Software is
12 | * furnished to do so, subject to the following conditions:
13 | *
14 | * The above copyright notice and this permission notice shall be included in
15 | * all copies or substantial portions of the Software.
16 | *
17 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23 | * THE SOFTWARE.
24 | */
25 |
26 | package org.mockito.kotlin
27 |
28 | import kotlinx.coroutines.CoroutineScope
29 | import kotlinx.coroutines.runBlocking
30 | import org.mockito.BDDMockito
31 | import org.mockito.BDDMockito.BDDMyOngoingStubbing
32 | import org.mockito.BDDMockito.Then
33 | import org.mockito.invocation.InvocationOnMock
34 | import org.mockito.kotlin.internal.SuspendableAnswer
35 | import org.mockito.stubbing.Answer
36 | import kotlin.reflect.KClass
37 |
38 | /**
39 | * Alias for [BDDMockito.given].
40 | */
41 | fun given(methodCall: T): BDDMockito.BDDMyOngoingStubbing {
42 | return BDDMockito.given(methodCall)
43 | }
44 |
45 | /**
46 | * Alias for [BDDMockito.given] with a lambda.
47 | */
48 | fun given(methodCall: () -> T): BDDMyOngoingStubbing {
49 | return given(methodCall())
50 | }
51 |
52 | /**
53 | * Alias for [BDDMockito.given] with a suspending lambda
54 | *
55 | * Warning: Only last method call can be stubbed in the function.
56 | * other method calls are ignored!
57 | */
58 | fun givenBlocking(methodCall: suspend CoroutineScope.() -> T): BDDMockito.BDDMyOngoingStubbing {
59 | return runBlocking { BDDMockito.given(methodCall()) }
60 | }
61 |
62 | /**
63 | * Alias for [BDDMockito.then].
64 | */
65 | fun then(mock: T): BDDMockito.Then {
66 | return BDDMockito.then(mock)
67 | }
68 |
69 | /**
70 | * Alias for [Then.should], with suspending lambda.
71 | */
72 | fun Then.shouldBlocking(f: suspend T.() -> R): R {
73 | val m = should()
74 | return runBlocking { m.f() }
75 | }
76 |
77 | /**
78 | * Alias for [BDDMyOngoingStubbing.will]
79 | * */
80 | infix fun BDDMyOngoingStubbing.will(value: Answer): BDDMockito.BDDMyOngoingStubbing {
81 | return will(value)
82 | }
83 |
84 | /**
85 | * Alias for [BBDMyOngoingStubbing.willAnswer], accepting a lambda.
86 | */
87 | infix fun BDDMyOngoingStubbing.willAnswer(value: (InvocationOnMock) -> T?): BDDMockito.BDDMyOngoingStubbing {
88 | return willAnswer { value(it) }
89 | }
90 |
91 | /**
92 | * Alias for [BBDMyOngoingStubbing.willAnswer], accepting a suspend lambda.
93 | */
94 | infix fun BDDMyOngoingStubbing.willSuspendableAnswer(value: suspend (InvocationOnMock) -> T?): BDDMockito.BDDMyOngoingStubbing {
95 | return willAnswer(SuspendableAnswer(value))
96 | }
97 |
98 | /**
99 | * Alias for [BBDMyOngoingStubbing.willReturn].
100 | */
101 | infix fun BDDMyOngoingStubbing.willReturn(value: () -> T): BDDMockito.BDDMyOngoingStubbing {
102 | return willReturn(value())
103 | }
104 |
105 | /**
106 | * Alias for [BBDMyOngoingStubbing.willThrow].
107 | */
108 | infix fun BDDMyOngoingStubbing.willThrow(value: () -> Throwable): BDDMockito.BDDMyOngoingStubbing {
109 | return willThrow(value())
110 | }
111 |
112 | /**
113 | * Sets a Throwable type to be thrown when the method is called.
114 | *
115 | * Alias for [BDDMyOngoingStubbing.willThrow]
116 | */
117 | infix fun BDDMyOngoingStubbing.willThrow(t: KClass): BDDMyOngoingStubbing {
118 | return willThrow(t.java)
119 | }
120 |
121 | /**
122 | * Sets Throwable classes to be thrown when the method is called.
123 | *
124 | * Alias for [BDDMyOngoingStubbing.willThrow]
125 | */
126 | fun BDDMyOngoingStubbing.willThrow(
127 | t: KClass,
128 | vararg ts: KClass
129 | ): BDDMyOngoingStubbing {
130 | return willThrow(t.java, *ts.map { it.java }.toTypedArray())
131 | }
132 |
133 | /**
134 | * Sets consecutive return values to be returned when the method is called.
135 | * Same as [BDDMyOngoingStubbing.willReturn], but accepts list instead of varargs.
136 | */
137 | inline infix fun BDDMyOngoingStubbing.willReturnConsecutively(ts: List): BDDMyOngoingStubbing {
138 | return willReturn(
139 | ts[0],
140 | *ts.drop(1).toTypedArray()
141 | )
142 | }
143 |
--------------------------------------------------------------------------------
/mockito-kotlin/src/main/kotlin/org/mockito/kotlin/Matchers.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * The MIT License
3 | *
4 | * Copyright (c) 2018 Niek Haarman
5 | * Copyright (c) 2007 Mockito contributors
6 | *
7 | * Permission is hereby granted, free of charge, to any person obtaining a copy
8 | * of this software and associated documentation files (the "Software"), to deal
9 | * in the Software without restriction, including without limitation the rights
10 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 | * copies of the Software, and to permit persons to whom the Software is
12 | * furnished to do so, subject to the following conditions:
13 | *
14 | * The above copyright notice and this permission notice shall be included in
15 | * all copies or substantial portions of the Software.
16 | *
17 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23 | * THE SOFTWARE.
24 | */
25 |
26 | package org.mockito.kotlin
27 |
28 | import org.mockito.ArgumentMatcher
29 | import org.mockito.ArgumentMatchers
30 | import org.mockito.kotlin.internal.createInstance
31 | import kotlin.reflect.KClass
32 |
33 | /** Object argument that is equal to the given value. */
34 | fun eq(value: T): T {
35 | return ArgumentMatchers.eq(value) ?: value
36 | }
37 |
38 | /** Object argument that is the same as the given value. */
39 | fun same(value: T): T {
40 | return ArgumentMatchers.same(value) ?: value
41 | }
42 |
43 | /** Matches any object, excluding nulls. */
44 | inline fun any(): T {
45 | return ArgumentMatchers.any(T::class.java) ?: createInstance()
46 | }
47 |
48 | /** Matches anything, including nulls. */
49 | inline fun anyOrNull(): T {
50 | return ArgumentMatchers.any() ?: createInstance()
51 | }
52 |
53 | /** Matches any vararg object, including nulls. */
54 | inline fun anyVararg(): T {
55 | return anyVararg(T::class)
56 | }
57 |
58 | fun anyVararg(clazz: KClass): T {
59 | return ArgumentMatchers.argThat(VarargMatcher(clazz.java)) ?: createInstance(clazz)
60 | }
61 |
62 | private class VarargMatcher(private val clazz: Class) : ArgumentMatcher {
63 | override fun matches(t: T): Boolean = true
64 |
65 | // In Java >= 12 you can do clazz.arrayClass()
66 | override fun type(): Class<*> = java.lang.reflect.Array.newInstance(clazz, 0).javaClass
67 | }
68 |
69 | /** Matches any array of type T. */
70 | inline fun anyArray(): Array {
71 | return ArgumentMatchers.any(Array::class.java) ?: arrayOf()
72 | }
73 |
74 | /**
75 | * Creates a custom argument matcher.
76 | * `null` values will never evaluate to `true`.
77 | *
78 | * @param predicate An extension function on [T] that returns `true` when a [T] matches the predicate.
79 | */
80 | inline fun argThat(noinline predicate: T.() -> Boolean): T {
81 | return ArgumentMatchers.argThat { arg: T? -> arg?.predicate() ?: false } ?: createInstance(
82 | T::class
83 | )
84 | }
85 |
86 | /**
87 | * Registers a custom ArgumentMatcher. The original Mockito function registers the matcher and returns null,
88 | * here the required type is returned.
89 | *
90 | * @param matcher The ArgumentMatcher on [T] to be registered.
91 | */
92 | inline fun argThat(matcher: ArgumentMatcher): T {
93 | return ArgumentMatchers.argThat(matcher) ?: createInstance()
94 | }
95 |
96 | /**
97 | * Alias for [argThat].
98 | *
99 | * Creates a custom argument matcher.
100 | * `null` values will never evaluate to `true`.
101 | *
102 | * @param predicate An extension function on [T] that returns `true` when a [T] matches the predicate.
103 | */
104 | inline fun argForWhich(noinline predicate: T.() -> Boolean): T {
105 | return argThat(predicate)
106 | }
107 |
108 | /**
109 | * Creates a custom argument matcher.
110 | * `null` values will never evaluate to `true`.
111 | *
112 | * @param predicate A function that returns `true` when given [T] matches the predicate.
113 | */
114 | inline fun argWhere(noinline predicate: (T) -> Boolean): T {
115 | return argThat(predicate)
116 | }
117 |
118 | /**
119 | * Argument that implements the given class.
120 | */
121 | inline fun isA(): T {
122 | return ArgumentMatchers.isA(T::class.java) ?: createInstance()
123 | }
124 |
125 | /**
126 | * `null` argument.
127 | */
128 | fun isNull(): T? = ArgumentMatchers.isNull()
129 |
130 | /**
131 | * Not `null` argument.
132 | */
133 | fun isNotNull(): T? {
134 | return ArgumentMatchers.isNotNull()
135 | }
136 |
137 | /**
138 | * Not `null` argument.
139 | */
140 | fun notNull(): T? {
141 | return ArgumentMatchers.notNull()
142 | }
143 |
144 | /**
145 | * Object argument that is reflection-equal to the given value with support for excluding
146 | * selected fields from a class.
147 | */
148 | inline fun refEq(value: T, vararg excludeFields: String): T {
149 | return ArgumentMatchers.refEq(value, *excludeFields) ?: createInstance()
150 | }
151 |
--------------------------------------------------------------------------------
/mockito-kotlin/src/main/kotlin/org/mockito/kotlin/AdditionalMatchers.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * The MIT License
3 | *
4 | * Copyright (c) 2024 Mockito contributors
5 | *
6 | * Permission is hereby granted, free of charge, to any person obtaining a copy
7 | * of this software and associated documentation files (the "Software"), to deal
8 | * in the Software without restriction, including without limitation the rights
9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 | * copies of the Software, and to permit persons to whom the Software is
11 | * furnished to do so, subject to the following conditions:
12 | *
13 | * The above copyright notice and this permission notice shall be included in
14 | * all copies or substantial portions of the Software.
15 | *
16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 | * THE SOFTWARE.
23 | */
24 |
25 | package org.mockito.kotlin
26 |
27 | import org.mockito.AdditionalMatchers
28 | import org.mockito.kotlin.internal.createInstance
29 | import kotlin.reflect.KClass
30 |
31 | /** comparable argument greater than or equal the given value. */
32 | inline fun > geq(value: T): T {
33 | return AdditionalMatchers.geq(value) ?: createInstance()
34 | }
35 |
36 | /** comparable argument greater than or equal to the given value. */
37 | inline fun > leq(value: T): T {
38 | return AdditionalMatchers.leq(value) ?: createInstance()
39 | }
40 |
41 | /** comparable argument greater than the given value. */
42 | inline fun > gt(value: T): T {
43 | return AdditionalMatchers.gt(value) ?: createInstance()
44 | }
45 |
46 | /** comparable argument less than the given value. */
47 | inline fun > lt(value: T): T {
48 | return AdditionalMatchers.lt(value) ?: createInstance()
49 | }
50 |
51 | /** comparable argument equals to the given value according to their compareTo method. */
52 | inline fun > cmpEq(value: T): T {
53 | return AdditionalMatchers.cmpEq(value) ?: createInstance()
54 | }
55 |
56 | /**
57 | * Any array argument that is equal to the given array, i.e. it has to have the same type, length,
58 | * and each element has to be equal.
59 | */
60 | inline fun aryEq(value: Array): Array {
61 | return AdditionalMatchers.aryEq(value) ?: createInstance()
62 | }
63 |
64 | /**
65 | * short array argument that is equal to the given array, i.e. it has to have the same length, and
66 | * each element has to be equal.
67 | */
68 | fun aryEq(value: ShortArray): ShortArray {
69 | return AdditionalMatchers.aryEq(value) ?: createInstance()
70 | }
71 |
72 | /**
73 | * long array argument that is equal to the given array, i.e. it has to have the same length, and
74 | * each element has to be equal.
75 | */
76 | fun aryEq(value: LongArray): LongArray {
77 | return AdditionalMatchers.aryEq(value) ?: createInstance()
78 | }
79 |
80 | /**
81 | * int array argument that is equal to the given array, i.e. it has to have the same length, and
82 | * each element has to be equal.
83 | */
84 | fun aryEq(value: IntArray): IntArray {
85 | return AdditionalMatchers.aryEq(value) ?: createInstance()
86 | }
87 |
88 | /**
89 | * float array argument that is equal to the given array, i.e. it has to have the same length, and
90 | * each element has to be equal.
91 | */
92 | fun aryEq(value: FloatArray): FloatArray {
93 | return AdditionalMatchers.aryEq(value) ?: createInstance()
94 | }
95 |
96 | /**
97 | * double array argument that is equal to the given array, i.e. it has to have the same length, and
98 | * each element has to be equal.
99 | */
100 | fun aryEq(value: DoubleArray): DoubleArray {
101 | return AdditionalMatchers.aryEq(value) ?: createInstance()
102 | }
103 |
104 | /**
105 | * char array argument that is equal to the given array, i.e. it has to have the same length, and
106 | * each element has to be equal.
107 | */
108 | fun aryEq(value: CharArray): CharArray {
109 | return AdditionalMatchers.aryEq(value) ?: createInstance()
110 | }
111 |
112 | /**
113 | * byte array argument that is equal to the given array, i.e. it has to have the same length, and
114 | * each element has to be equal.
115 | */
116 | fun aryEq(value: ByteArray): ByteArray {
117 | return AdditionalMatchers.aryEq(value) ?: createInstance()
118 | }
119 |
120 | /**
121 | * boolean array argument that is equal to the given array, i.e. it has to have the same length, and
122 | * each element has to be equal.
123 | */
124 | fun aryEq(value: BooleanArray): BooleanArray {
125 | return AdditionalMatchers.aryEq(value) ?: createInstance()
126 | }
127 |
128 | /** String argument that contains a substring that matches the given regular expression. */
129 | fun find(regex: Regex): String {
130 | return AdditionalMatchers.find(regex.pattern) ?: ""
131 | }
132 |
133 | /** argument that matches both given argument matchers. */
134 | inline fun and(left: T, right: T): T {
135 | return AdditionalMatchers.and(left, right) ?: createInstance()
136 | }
137 |
138 | /** argument that matches both given argument matchers. */
139 | inline fun or(left: T, right: T): T {
140 | return AdditionalMatchers.or(left, right) ?: createInstance()
141 | }
142 |
143 | /** argument that does not match the given argument matcher. */
144 | inline fun not(matcher: T): T {
145 | return AdditionalMatchers.not(matcher) ?: createInstance()
146 | }
147 |
148 | /**
149 | * float argument that has an absolute difference to the given value that is
150 | * less than the given delta details.
151 | */
152 | fun eq(value: Double, delta: Double): Double {
153 | return AdditionalMatchers.eq(value, delta) ?: 0.0
154 | }
155 |
156 | /**
157 | * double argument that has an absolute difference to the given value that
158 | * is less than the given delta details.
159 | */
160 | fun eq(value: Float, delta: Float): Float {
161 | return AdditionalMatchers.eq(value, delta) ?: 0.0f
162 | }
163 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | #
4 | # Copyright 2015 the original author or authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 |
19 | ##############################################################################
20 | ##
21 | ## Gradle start up script for UN*X
22 | ##
23 | ##############################################################################
24 |
25 | # Attempt to set APP_HOME
26 | # Resolve links: $0 may be a link
27 | PRG="$0"
28 | # Need this for relative symlinks.
29 | while [ -h "$PRG" ] ; do
30 | ls=`ls -ld "$PRG"`
31 | link=`expr "$ls" : '.*-> \(.*\)$'`
32 | if expr "$link" : '/.*' > /dev/null; then
33 | PRG="$link"
34 | else
35 | PRG=`dirname "$PRG"`"/$link"
36 | fi
37 | done
38 | SAVED="`pwd`"
39 | cd "`dirname \"$PRG\"`/" >/dev/null
40 | APP_HOME="`pwd -P`"
41 | cd "$SAVED" >/dev/null
42 |
43 | APP_NAME="Gradle"
44 | APP_BASE_NAME=`basename "$0"`
45 |
46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
48 |
49 | # Use the maximum available, or set MAX_FD != -1 to use that value.
50 | MAX_FD="maximum"
51 |
52 | warn () {
53 | echo "$*"
54 | }
55 |
56 | die () {
57 | echo
58 | echo "$*"
59 | echo
60 | exit 1
61 | }
62 |
63 | # OS specific support (must be 'true' or 'false').
64 | cygwin=false
65 | msys=false
66 | darwin=false
67 | nonstop=false
68 | case "`uname`" in
69 | CYGWIN* )
70 | cygwin=true
71 | ;;
72 | Darwin* )
73 | darwin=true
74 | ;;
75 | MINGW* )
76 | msys=true
77 | ;;
78 | NONSTOP* )
79 | nonstop=true
80 | ;;
81 | esac
82 |
83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
84 |
85 |
86 | # Determine the Java command to use to start the JVM.
87 | if [ -n "$JAVA_HOME" ] ; then
88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
89 | # IBM's JDK on AIX uses strange locations for the executables
90 | JAVACMD="$JAVA_HOME/jre/sh/java"
91 | else
92 | JAVACMD="$JAVA_HOME/bin/java"
93 | fi
94 | if [ ! -x "$JAVACMD" ] ; then
95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
96 |
97 | Please set the JAVA_HOME variable in your environment to match the
98 | location of your Java installation."
99 | fi
100 | else
101 | JAVACMD="java"
102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
103 |
104 | Please set the JAVA_HOME variable in your environment to match the
105 | location of your Java installation."
106 | fi
107 |
108 | # Increase the maximum file descriptors if we can.
109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
110 | MAX_FD_LIMIT=`ulimit -H -n`
111 | if [ $? -eq 0 ] ; then
112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
113 | MAX_FD="$MAX_FD_LIMIT"
114 | fi
115 | ulimit -n $MAX_FD
116 | if [ $? -ne 0 ] ; then
117 | warn "Could not set maximum file descriptor limit: $MAX_FD"
118 | fi
119 | else
120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
121 | fi
122 | fi
123 |
124 | # For Darwin, add options to specify how the application appears in the dock
125 | if $darwin; then
126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
127 | fi
128 |
129 | # For Cygwin or MSYS, switch paths to Windows format before running java
130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
133 |
134 | JAVACMD=`cygpath --unix "$JAVACMD"`
135 |
136 | # We build the pattern for arguments to be converted via cygpath
137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
138 | SEP=""
139 | for dir in $ROOTDIRSRAW ; do
140 | ROOTDIRS="$ROOTDIRS$SEP$dir"
141 | SEP="|"
142 | done
143 | OURCYGPATTERN="(^($ROOTDIRS))"
144 | # Add a user-defined pattern to the cygpath arguments
145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
147 | fi
148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
149 | i=0
150 | for arg in "$@" ; do
151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
153 |
154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
156 | else
157 | eval `echo args$i`="\"$arg\""
158 | fi
159 | i=`expr $i + 1`
160 | done
161 | case $i in
162 | 0) set -- ;;
163 | 1) set -- "$args0" ;;
164 | 2) set -- "$args0" "$args1" ;;
165 | 3) set -- "$args0" "$args1" "$args2" ;;
166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;;
167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
172 | esac
173 | fi
174 |
175 | # Escape application args
176 | save () {
177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
178 | echo " "
179 | }
180 | APP_ARGS=`save "$@"`
181 |
182 | # Collect all arguments for the java command, following the shell quoting and substitution rules
183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
184 |
185 | exec "$JAVACMD" "$@"
186 |
--------------------------------------------------------------------------------
/mockito-kotlin/src/main/kotlin/org/mockito/kotlin/ArgumentCaptor.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * The MIT License
3 | *
4 | * Copyright (c) 2018 Niek Haarman
5 | * Copyright (c) 2007 Mockito contributors
6 | *
7 | * Permission is hereby granted, free of charge, to any person obtaining a copy
8 | * of this software and associated documentation files (the "Software"), to deal
9 | * in the Software without restriction, including without limitation the rights
10 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 | * copies of the Software, and to permit persons to whom the Software is
12 | * furnished to do so, subject to the following conditions:
13 | *
14 | * The above copyright notice and this permission notice shall be included in
15 | * all copies or substantial portions of the Software.
16 | *
17 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23 | * THE SOFTWARE.
24 | */
25 |
26 | package org.mockito.kotlin
27 |
28 | import org.mockito.kotlin.internal.createInstance
29 | import org.mockito.ArgumentCaptor
30 | import java.lang.reflect.Array
31 | import kotlin.reflect.KClass
32 |
33 | /**
34 | * Creates a [KArgumentCaptor] for given type.
35 | */
36 | inline fun argumentCaptor(): KArgumentCaptor {
37 | return KArgumentCaptor(ArgumentCaptor.forClass(T::class.java), T::class)
38 | }
39 |
40 | /**
41 | * Creates 2 [KArgumentCaptor]s for given types.
42 | */
43 | inline fun argumentCaptor(
44 | a: KClass = A::class,
45 | b: KClass = B::class
46 | ): Pair, KArgumentCaptor> {
47 | return Pair(
48 | KArgumentCaptor(ArgumentCaptor.forClass(a.java), a),
49 | KArgumentCaptor(ArgumentCaptor.forClass(b.java), b)
50 | )
51 | }
52 |
53 | /**
54 | * Creates 3 [KArgumentCaptor]s for given types.
55 | */
56 | inline fun argumentCaptor(
57 | a: KClass = A::class,
58 | b: KClass = B::class,
59 | c: KClass = C::class
60 | ): Triple, KArgumentCaptor, KArgumentCaptor> {
61 | return Triple(
62 | KArgumentCaptor(ArgumentCaptor.forClass(a.java), a),
63 | KArgumentCaptor(ArgumentCaptor.forClass(b.java), b),
64 | KArgumentCaptor(ArgumentCaptor.forClass(c.java), c)
65 | )
66 | }
67 |
68 | class ArgumentCaptorHolder4(
69 | val first: A,
70 | val second: B,
71 | val third: C,
72 | val fourth: D
73 | ) {
74 |
75 | operator fun component1() = first
76 | operator fun component2() = second
77 | operator fun component3() = third
78 | operator fun component4() = fourth
79 | }
80 |
81 | class ArgumentCaptorHolder5(
82 | val first: A,
83 | val second: B,
84 | val third: C,
85 | val fourth: D,
86 | val fifth: E
87 | ) {
88 |
89 | operator fun component1() = first
90 | operator fun component2() = second
91 | operator fun component3() = third
92 | operator fun component4() = fourth
93 | operator fun component5() = fifth
94 | }
95 |
96 | /**
97 | * Creates 4 [KArgumentCaptor]s for given types.
98 | */
99 | inline fun argumentCaptor(
100 | a: KClass = A::class,
101 | b: KClass = B::class,
102 | c: KClass = C::class,
103 | d: KClass = D::class
104 | ): ArgumentCaptorHolder4, KArgumentCaptor, KArgumentCaptor, KArgumentCaptor> {
105 | return ArgumentCaptorHolder4(
106 | KArgumentCaptor(ArgumentCaptor.forClass(a.java), a),
107 | KArgumentCaptor(ArgumentCaptor.forClass(b.java), b),
108 | KArgumentCaptor(ArgumentCaptor.forClass(c.java), c),
109 | KArgumentCaptor(ArgumentCaptor.forClass(d.java), d)
110 | )
111 | }
112 |
113 | /**
114 | * Creates 4 [KArgumentCaptor]s for given types.
115 | */
116 | inline fun argumentCaptor(
117 | a: KClass = A::class,
118 | b: KClass = B::class,
119 | c: KClass = C::class,
120 | d: KClass