├── app
├── .gitignore
├── src
│ ├── main
│ │ ├── res
│ │ │ ├── values
│ │ │ │ ├── strings.xml
│ │ │ │ ├── colors.xml
│ │ │ │ └── styles.xml
│ │ │ ├── mipmap-hdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-mdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xhdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xxhdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xxxhdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-anydpi-v26
│ │ │ │ ├── ic_launcher.xml
│ │ │ │ └── ic_launcher_round.xml
│ │ │ ├── drawable-v24
│ │ │ │ └── ic_launcher_foreground.xml
│ │ │ └── drawable
│ │ │ │ └── ic_launcher_background.xml
│ │ ├── AndroidManifest.xml
│ │ └── java
│ │ │ └── de
│ │ │ └── mobilej
│ │ │ └── kmockit
│ │ │ └── SampleCode.kt
│ └── test
│ │ └── java
│ │ └── de
│ │ └── mobilej
│ │ └── kmockit
│ │ └── ExampleUnitTest.kt
├── proguard-rules.pro
└── build.gradle
├── jvmApp
├── .gitignore
├── build.gradle
└── src
│ ├── main
│ └── kotlin
│ │ └── de
│ │ └── mobilej
│ │ └── kmockit
│ │ └── SampleCode.kt
│ └── test
│ └── kotlin
│ └── de
│ └── mobilej
│ └── kmockit
│ └── ExampleUnitTest.kt
├── kmockit
├── .gitignore
├── build.gradle
└── src
│ └── main
│ └── java
│ └── de
│ └── mobilej
│ └── kmockit
│ ├── DelegateMethod.java
│ └── KMockit.kt
├── settings.gradle
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── .gitignore
├── gradle.properties
├── README.md
├── gradlew.bat
├── gradlew
└── LICENSE.txt
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 | .idea
3 |
--------------------------------------------------------------------------------
/jvmApp/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 | .idea
3 |
--------------------------------------------------------------------------------
/kmockit/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 | .idea
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app', ':kmockit', 'jvmApp'
2 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | KMockit
3 |
4 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bjoernQ/kmockit/master/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | .idea
5 | .DS_Store
6 | /build
7 | /captures
8 | .externalNativeBuild
9 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bjoernQ/kmockit/master/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bjoernQ/kmockit/master/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bjoernQ/kmockit/master/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bjoernQ/kmockit/master/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bjoernQ/kmockit/master/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bjoernQ/kmockit/master/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bjoernQ/kmockit/master/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bjoernQ/kmockit/master/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bjoernQ/kmockit/master/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bjoernQ/kmockit/master/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Wed May 16 08:32:28 CEST 2018
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-all.zip
7 |
--------------------------------------------------------------------------------
/jvmApp/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: "kotlin"
2 |
3 | dependencies {
4 | implementation fileTree(dir: 'libs', include: ['*.jar'])
5 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
6 | testImplementation 'junit:junit:4.12'
7 | testImplementation project(':kmockit')
8 | }
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
11 |
12 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | org.gradle.jvmargs=-Xmx1536m
13 |
14 | # When configured, Gradle will run in incubating parallel mode.
15 | # This option should only be used with decoupled projects. More details, visit
16 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
17 | # org.gradle.parallel=true
18 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 | apply plugin: 'kotlin-android'
3 | apply plugin: 'kotlin-android-extensions'
4 |
5 | android {
6 | compileSdkVersion 26
7 | defaultConfig {
8 | applicationId "de.mobilej.kmockit"
9 | minSdkVersion 19
10 | targetSdkVersion 26
11 | versionCode 1
12 | versionName "1.0"
13 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
14 | }
15 | buildTypes {
16 | release {
17 | minifyEnabled false
18 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
19 | }
20 | }
21 | }
22 |
23 | dependencies {
24 | implementation fileTree(dir: 'libs', include: ['*.jar'])
25 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
26 | implementation 'com.android.support:appcompat-v7:26.1.0'
27 | testImplementation 'junit:junit:4.12'
28 | testImplementation project(':kmockit')
29 | }
30 |
--------------------------------------------------------------------------------
/kmockit/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'java-library'
2 | apply plugin: 'kotlin'
3 | apply plugin: 'com.github.dcendents.android-maven'
4 |
5 | group = 'com.github.bjoernQ'
6 |
7 | dependencies {
8 | implementation fileTree(dir: 'libs', include: ['*.jar'])
9 |
10 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
11 | api "org.jmockit:jmockit:1.38"
12 | implementation "net.bytebuddy:byte-buddy:1.7.9"
13 | implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"
14 | }
15 |
16 | task sourcesJar(type: Jar, dependsOn: classes) {
17 | classifier = 'sources'
18 | from sourceSets.main.allSource
19 | }
20 |
21 | artifacts {
22 | archives sourcesJar
23 | }
24 |
25 | install {
26 | repositories.mavenInstaller {
27 | pom.project {
28 | licenses {
29 | license {
30 | name 'The Apache Software License, Version 2.0'
31 | url 'http://www.apache.org/licenses/LICENSE-2.0.txt'
32 | distribution 'repo'
33 | }
34 | }
35 | }
36 | }
37 | }
38 |
39 | sourceCompatibility = "1.7"
40 | targetCompatibility = "1.7"
41 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # KMockit
2 |
3 | Kotlin friendly wrapper for JMockit
4 |
5 | ## About
6 |
7 | As it turned out JMockit works fine for Kotlin on the JVM.
8 | It works very well but the API is designed to look and feel good in Java.
9 | This is a thin wrapper for JMockit to make it feel more natural in Kotlin.
10 |
11 | Here is an example of how it looks like
12 | ```kotlin
13 | every { myDependency.doSomething(anyString()) } returns { "test" }
14 | every { myDependency.anotherMethod(anyInt()) } returns { 5 }
15 |
16 | val result = sut.myMethod("myVal")
17 | assertEquals("test542", result)
18 |
19 | verifications {
20 | once { myDependency.doSomething(anyString()) }
21 | once { myDependency.anotherMethod(10) }
22 | never { myDependency.unused() }
23 | }
24 | ```
25 |
26 | It also offers a different way for MockUp
27 | ```kotlin
28 | mockup {
29 | on(Evil.Companion::companion) { "mockup" }
30 | }
31 |
32 | mockup {
33 | on(Evil::theAnswer) {
34 | 99
35 | }
36 | on(Evil::another) {
37 | "NOTHING" + it[0]
38 | }
39 | }
40 |
41 | assertEquals("mockup", Evil.Companion.companion())
42 | assertEquals(99, Evil().theAnswer("?"))
43 | assertEquals("NOTHING1", Evil().another(1, 2))
44 | ```
45 |
46 | For more examples have a look at the sample app's ExampleUnitTest.kt
47 |
48 | ## Versioning
49 |
50 | As long as it's below 1.0.0 the API isn't guaranteed to be stable and there is no strong versioning scheme applied.
51 |
52 | Starting with 1.0.0 the API will be stable and semantic version is applied.
53 |
54 | ## Get it
55 |
56 | For now it's available via JitPack only.
--------------------------------------------------------------------------------
/app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
12 |
13 |
19 |
22 |
25 |
26 |
27 |
28 |
34 |
35 |
--------------------------------------------------------------------------------
/jvmApp/src/main/kotlin/de/mobilej/kmockit/SampleCode.kt:
--------------------------------------------------------------------------------
1 | package de.mobilej.kmockit
2 |
3 | class Evil {
4 |
5 | companion object {
6 | fun companion(): String {
7 | return "companion"
8 | }
9 | }
10 |
11 | fun theAnswer(value: String): Int {
12 | return 42
13 | }
14 |
15 | fun another(value: Int, value2: Int): String {
16 | return "$value + $value2 = ${value + value2}"
17 | }
18 | }
19 |
20 | class UnderTest(val dependency: MyDependency) {
21 |
22 | fun myMethod(value: String): String {
23 | return dependency.doSomething(value) + dependency.anotherMethod(10) + Evil().theAnswer("?")
24 | }
25 |
26 | fun myMethod2(value: String): String {
27 | return dependency.doSomething(value) + dependency.doSomething(value)
28 | }
29 |
30 | fun myMethodInt(i: Int): Int {
31 | return dependency.doInt(i);
32 | }
33 |
34 | fun myMethodBoolean(v: Boolean): Boolean {
35 | return dependency.doBoolean(v);
36 | }
37 |
38 | fun myMethodLong(v: Long): Long {
39 | return dependency.doLong(v);
40 | }
41 |
42 | fun myMethodChar(v: Char): Char {
43 | return dependency.doChar(v);
44 | }
45 |
46 | fun myMethodFloat(v: Float): Float {
47 | return dependency.doFloat(v);
48 | }
49 |
50 | fun myMethodDouble(v: Double): Double {
51 | return dependency.doDouble(v);
52 | }
53 |
54 | fun myMethodShort(v: Short): Short {
55 | return dependency.doShort(v);
56 | }
57 |
58 | fun myMethodByte(v: Byte): Byte {
59 | return dependency.doByte(v);
60 | }
61 | }
62 |
63 | class MyDependency {
64 | fun doSomething(value: String): String {
65 | return value.reversed()
66 | }
67 |
68 | fun anotherMethod(value: Int): String {
69 | return value.toString()
70 | }
71 |
72 | fun unused() {
73 | // nothing
74 | }
75 |
76 | fun doInt(i: Int): Int {
77 | return i;
78 | }
79 |
80 | fun doBoolean(b: Boolean): Boolean {
81 | return b;
82 | }
83 |
84 | fun doLong(v: Long): Long {
85 | return v;
86 | }
87 |
88 | fun doFloat(v: Float): Float {
89 | return v;
90 | }
91 |
92 | fun doDouble(v: Double): Double {
93 | return v;
94 | }
95 |
96 | fun doByte(v: Byte): Byte {
97 | return v;
98 | }
99 |
100 | fun doShort(v: Short): Short {
101 | return v;
102 | }
103 |
104 | fun doChar(v: Char): Char {
105 | return v;
106 | }
107 |
108 | }
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/kmockit/src/main/java/de/mobilej/kmockit/DelegateMethod.java:
--------------------------------------------------------------------------------
1 | package de.mobilej.kmockit;
2 |
3 |
4 | import net.bytebuddy.implementation.bind.annotation.AllArguments;
5 | import net.bytebuddy.implementation.bind.annotation.Origin;
6 | import net.bytebuddy.implementation.bind.annotation.RuntimeType;
7 | import net.bytebuddy.implementation.bind.annotation.This;
8 |
9 | import org.jetbrains.annotations.NotNull;
10 | import org.jetbrains.annotations.Nullable;
11 |
12 | import java.lang.reflect.Constructor;
13 | import java.lang.reflect.Method;
14 | import java.util.HashMap;
15 |
16 | import kotlin.jvm.functions.Function1;
17 |
18 | // this is Java since it didn't worked when using Kotlin
19 | public class DelegateMethod {
20 |
21 | private static HashMap>> methodToFunction = new HashMap<>();
22 |
23 | @RuntimeType
24 | public static Object perform(@Origin Method origin, @This Object thisRef, @AllArguments Object... args) {
25 | HashMap> map = methodToFunction.get(origin.getDeclaringClass().getName());
26 | if (map != null) {
27 | Function1 super Object[], ?> function = map.get(createSignature(origin));
28 | if (function != null) {
29 | return function.invoke(args);
30 | }
31 | }
32 |
33 | return 0;
34 | }
35 |
36 | public static void add(String clzName, @Nullable Object javaMethod, @NotNull Function1 super Object[], ? extends Object> function) {
37 | HashMap> map = methodToFunction.get(clzName);
38 | if (map == null) {
39 | map = new HashMap<>();
40 | methodToFunction.put(clzName, map);
41 | }
42 |
43 | map.put(createSignature(javaMethod), function);
44 | }
45 |
46 | private static String createSignature(@Nullable Object method) {
47 | if (method == null) {
48 | return "null";
49 | }
50 |
51 | if (method instanceof Method) {
52 | Method javaMethod = (Method) method;
53 |
54 | StringBuilder params = new StringBuilder();
55 | for (Class> paramType : javaMethod.getParameterTypes()) {
56 | params.append(paramType.getSimpleName());
57 | }
58 |
59 | String retType = javaMethod.getReturnType().toString();
60 |
61 | if (javaMethod.getName().equals("$init")) {
62 | retType = "_";
63 | }
64 |
65 | return javaMethod.getName() + retType + params.toString();
66 | }
67 |
68 | Constructor javaMethod = (Constructor) method;
69 | StringBuilder params = new StringBuilder();
70 | for (Class> paramType : javaMethod.getParameterTypes()) {
71 | params.append(paramType.getSimpleName());
72 | }
73 | return "$init_" + params.toString();
74 | }
75 |
76 | }
77 |
--------------------------------------------------------------------------------
/app/src/main/java/de/mobilej/kmockit/SampleCode.kt:
--------------------------------------------------------------------------------
1 | package de.mobilej.kmockit
2 |
3 | class Evil {
4 |
5 | companion object {
6 | fun companion(): String {
7 | return "companion"
8 | }
9 | }
10 |
11 | fun theAnswer(value: String): Int {
12 | return 42
13 | }
14 |
15 | fun another(value: Int, value2: Int): String {
16 | return "$value + $value2 = ${value + value2}"
17 | }
18 |
19 | fun ambiguous(value: Int): String {
20 | return value.toString()
21 | }
22 |
23 | fun ambiguous(value: String): String {
24 | return value
25 | }
26 | }
27 |
28 | class AnotherClass {
29 |
30 | var value: String
31 |
32 | constructor(v: String) {
33 | value = v
34 | }
35 |
36 | fun myMethod(): String {
37 | return "Value is $value"
38 | }
39 | }
40 |
41 | fun AnotherClass.extension(i: Int): String {
42 | return "$i ${this.myMethod()}"
43 | }
44 |
45 | fun topLevel(v: String): String {
46 | return ">>$v<<"
47 | }
48 |
49 | class UnderTest(val dependency: MyDependency) {
50 |
51 | fun myMethod(value: String): String {
52 | return dependency.doSomething(value) + dependency.anotherMethod(10) + Evil().theAnswer("?")
53 | }
54 |
55 | fun myMethod2(value: String): String {
56 | return dependency.doSomething(value) + dependency.doSomething(value)
57 | }
58 |
59 | fun myMethod3(value: String): String {
60 | return dependency.doSomethingAgain(5, value) + dependency.doSomethingAgain(5, value)
61 | }
62 |
63 | fun myMethod4(block: () -> String): String {
64 | return dependency.higherOrderFunction(block)
65 | }
66 |
67 | fun myMethod5(block: (Int, String) -> Long): String {
68 | return dependency.higherOrderFunction2(block)
69 | }
70 |
71 | fun myMethod6(block: (Int, String) -> Long): String {
72 | return dependency.higherOrderFunction3(21, 42, block)
73 | }
74 |
75 | fun myMethodInt(i: Int): Int {
76 | return dependency.doInt(i);
77 | }
78 |
79 | fun myMethodBoolean(v: Boolean): Boolean {
80 | return dependency.doBoolean(v);
81 | }
82 |
83 | fun myMethodLong(v: Long): Long {
84 | return dependency.doLong(v);
85 | }
86 |
87 | fun myMethodChar(v: Char): Char {
88 | return dependency.doChar(v);
89 | }
90 |
91 | fun myMethodFloat(v: Float): Float {
92 | return dependency.doFloat(v);
93 | }
94 |
95 | fun myMethodDouble(v: Double): Double {
96 | return dependency.doDouble(v);
97 | }
98 |
99 | fun myMethodShort(v: Short): Short {
100 | return dependency.doShort(v);
101 | }
102 |
103 | fun myMethodByte(v: Byte): Byte {
104 | return dependency.doByte(v);
105 | }
106 | }
107 |
108 | class MyDependency {
109 | fun doSomething(value: String): String {
110 | return value.reversed()
111 | }
112 |
113 | fun anotherMethod(value: Int): String {
114 | return value.toString()
115 | }
116 |
117 | fun doSomethingAgain(i: Int, v: String): String {
118 | return v
119 | }
120 |
121 | fun higherOrderFunction(block: () -> String): String {
122 | return block()
123 | }
124 |
125 | fun higherOrderFunction2(block: (Int, String) -> Long): String {
126 | return block(5, "Hello").toString()
127 | }
128 |
129 | fun higherOrderFunction3(p1: Int, p2: Int, block: (Int, String) -> Long): String {
130 | return block(5, "Hello").toString()
131 | }
132 |
133 | fun unused() {
134 | // nothing
135 | }
136 |
137 | fun doInt(i: Int): Int {
138 | return i;
139 | }
140 |
141 | fun doBoolean(b: Boolean): Boolean {
142 | return b;
143 | }
144 |
145 | fun doLong(v: Long): Long {
146 | return v;
147 | }
148 |
149 | fun doFloat(v: Float): Float {
150 | return v;
151 | }
152 |
153 | fun doDouble(v: Double): Double {
154 | return v;
155 | }
156 |
157 | fun doByte(v: Byte): Byte {
158 | return v;
159 | }
160 |
161 | fun doShort(v: Short): Short {
162 | return v;
163 | }
164 |
165 | fun doChar(v: Char): Char {
166 | return v;
167 | }
168 |
169 | }
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/jvmApp/src/test/kotlin/de/mobilej/kmockit/ExampleUnitTest.kt:
--------------------------------------------------------------------------------
1 | package de.mobilej.kmockit
2 |
3 | import junit.framework.Assert.assertEquals
4 | import mockit.Injectable
5 | import mockit.Tested
6 | import mockit.integration.junit4.JMockit
7 | import org.junit.Test
8 | import org.junit.runner.RunWith
9 |
10 | @RunWith(JMockit::class)
11 | class ExampleUnitTest {
12 |
13 | @Injectable
14 | private lateinit var myDependency: MyDependency
15 |
16 | @Tested
17 | private lateinit var sut: UnderTest
18 |
19 | @Test
20 | fun simpleTest() {
21 | every { myDependency.doSomething(anyString()) } returns { "test" }
22 | every { myDependency.anotherMethod(anyInt()) } returns { 5 }
23 |
24 | val result = sut.myMethod("myVal")
25 | assertEquals("test542", result)
26 |
27 | verifications {
28 | once { myDependency.doSomething(anyString()) }
29 | once { myDependency.anotherMethod(10) }
30 | never { myDependency.unused() }
31 | }
32 | }
33 |
34 | @Test
35 | fun simpleTest2() {
36 | every { myDependency.anotherMethod(anyInt()) } returns { 5 }
37 | every { myDependency.doSomething(anyString()) } answers { "test" }
38 |
39 | val result = sut.myMethod("myVal")
40 | assertEquals("test542", result)
41 |
42 | val holder = mutableListOf()
43 | verifications {
44 | once { myDependency.doSomething(capture(holder)) }
45 | once { myDependency.anotherMethod(10) }
46 | never { myDependency.unused() }
47 | }
48 |
49 | assertEquals("myVal", holder[0])
50 | }
51 |
52 | @Test
53 | fun simpleTest3() {
54 |
55 | mockup {
56 | on(Evil.Companion::companion) { "mockup" }
57 | }
58 |
59 | mockup {
60 | on(Evil::theAnswer) {
61 | 99
62 | }
63 | on(Evil::another) {
64 | "NOTHING" + it[0]
65 | }
66 | }
67 |
68 | assertEquals("mockup", Evil.Companion.companion())
69 | assertEquals(99, Evil().theAnswer("?"))
70 | assertEquals("NOTHING1", Evil().another(1, 2))
71 | }
72 |
73 | @Test
74 | fun simpleTest4() {
75 | every { myDependency.doSomething(anyString()) } returnsAll listOf(
76 | { "test" },
77 | { "TEST" }
78 | )
79 |
80 | val result = sut.myMethod2("myVal")
81 | assertEquals("testTEST", result)
82 |
83 | verifications {
84 | twice { myDependency.doSomething(anyString()) }
85 | never { myDependency.unused() }
86 | }
87 | }
88 |
89 | @Test(expected = RuntimeException::class)
90 | fun simpleTest5() {
91 | every { myDependency.doSomething(anyString()) } answers {
92 | throw RuntimeException()
93 | @Suppress("unreachable_code")
94 | ""
95 | }
96 |
97 | sut.myMethod2("myVal")
98 | }
99 |
100 | @Test
101 | fun simpleTest6() {
102 | every { myDependency.doSomething(argThat { it == "myVal" }) } returns { "test" }
103 |
104 | val result = sut.myMethod2("myVal")
105 | assertEquals("testtest", result)
106 |
107 | verifications {
108 | twice { myDependency.doSomething(anyString()) }
109 | }
110 | }
111 |
112 | @Test
113 | fun simpleTest7() {
114 | every { myDependency.doInt(anyInt()) } returns { 22 }
115 |
116 | val result = sut.myMethodInt(55)
117 | assertEquals(22, result)
118 |
119 | verifications {
120 | once { myDependency.doInt(anyInt()) }
121 | }
122 | }
123 |
124 | @Test
125 | fun simpleTest8() {
126 | every { myDependency.doLong(anyLong()) } returns { 22L }
127 |
128 | val result = sut.myMethodLong(55L)
129 | assertEquals(22L, result)
130 |
131 | verifications {
132 | once { myDependency.doLong(anyLong()) }
133 | }
134 | }
135 |
136 | @Test
137 | fun simpleTest9() {
138 | every { myDependency.doBoolean(anyBoolean()) } returns { false }
139 |
140 | val result = sut.myMethodBoolean(true)
141 | assertEquals(false, result)
142 |
143 | verifications {
144 | once { myDependency.doBoolean(anyBoolean()) }
145 | }
146 | }
147 |
148 | @Test
149 | fun simpleTest10() {
150 | every { myDependency.doChar(anyChar()) } returns { 'x' }
151 |
152 | val result = sut.myMethodChar('a')
153 | assertEquals('x', result)
154 |
155 | verifications {
156 | once { myDependency.doChar(anyChar()) }
157 | }
158 | }
159 |
160 | @Test
161 | fun simpleTest11() {
162 | every { myDependency.doFloat(anyFloat()) } returns { 22.0F }
163 |
164 | val result = sut.myMethodFloat(15F)
165 | assertEquals(22.0F, result, 1F)
166 |
167 | verifications {
168 | once { myDependency.doFloat(anyFloat()) }
169 | }
170 | }
171 |
172 | @Test
173 | fun simpleTest12() {
174 | every { myDependency.doDouble(anyDouble()) } returns { 22.0 }
175 |
176 | val result = sut.myMethodDouble(15.0)
177 | assertEquals(22.0, result, 1.0)
178 |
179 | verifications {
180 | once { myDependency.doDouble(anyDouble()) }
181 | }
182 | }
183 |
184 | @Test
185 | fun simpleTest13() {
186 | every { myDependency.doShort(anyShort()) } returns { 22.toShort() }
187 |
188 | val result = sut.myMethodShort(15.toShort())
189 | assertEquals(22.toShort(), result)
190 |
191 | verifications {
192 | once { myDependency.doShort(anyShort()) }
193 | }
194 | }
195 |
196 | @Test
197 | fun simpleTest14() {
198 | every { myDependency.doByte(anyByte()) } returns { 22.toByte() }
199 |
200 | val result = sut.myMethodByte(15.toByte())
201 | assertEquals(22.toByte(), result)
202 |
203 | verifications {
204 | once { myDependency.doByte(anyByte()) }
205 | }
206 | }
207 | }
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
11 |
16 |
21 |
26 |
31 |
36 |
41 |
46 |
51 |
56 |
61 |
66 |
71 |
76 |
81 |
86 |
91 |
96 |
101 |
106 |
111 |
116 |
121 |
126 |
131 |
136 |
141 |
146 |
151 |
156 |
161 |
166 |
171 |
172 |
--------------------------------------------------------------------------------
/app/src/test/java/de/mobilej/kmockit/ExampleUnitTest.kt:
--------------------------------------------------------------------------------
1 | package de.mobilej.kmockit
2 |
3 | import junit.framework.Assert.assertEquals
4 | import junit.framework.Assert.assertTrue
5 | import mockit.Injectable
6 | import mockit.Tested
7 | import mockit.integration.junit4.JMockit
8 | import org.junit.Test
9 | import org.junit.runner.RunWith
10 |
11 | @RunWith(JMockit::class)
12 | class ExampleUnitTest {
13 |
14 | @Injectable
15 | private lateinit var myDependency: MyDependency
16 |
17 | @Tested
18 | private lateinit var sut: UnderTest
19 |
20 | @Test
21 | fun simpleTest() {
22 | every { myDependency.doSomething(anyString()) } returns { "test" }
23 | every { myDependency.anotherMethod(anyInt()) } returns { 5 }
24 |
25 | val result = sut.myMethod("myVal")
26 | assertEquals("test542", result)
27 |
28 | verifications {
29 | once { myDependency.doSomething(anyString()) }
30 | once { myDependency.anotherMethod(10) }
31 | never { myDependency.unused() }
32 | }
33 | }
34 |
35 | @Test
36 | fun simpleTest2() {
37 | every { myDependency.anotherMethod(anyInt()) } returns { 5 }
38 | every { myDependency.doSomething(anyString()) } answers { "test" }
39 |
40 | val result = sut.myMethod("myVal")
41 | assertEquals("test542", result)
42 |
43 | val holder = mutableListOf()
44 | verifications {
45 | once { myDependency.doSomething(capture(holder)) }
46 | once { myDependency.anotherMethod(10) }
47 | never { myDependency.unused() }
48 | }
49 |
50 | assertEquals("myVal", holder[0])
51 | }
52 |
53 | @Test
54 | fun simpleTest3() {
55 |
56 | mockup {
57 | on(Evil.Companion::companion) { "mockup" }
58 | }
59 |
60 | mockup {
61 | on(Evil::theAnswer) {
62 | 99
63 | }
64 | on(Evil::another) {
65 | "NOTHING" + it[0]
66 | }
67 | }
68 |
69 | assertEquals("mockup", Evil.Companion.companion())
70 | assertEquals(99, Evil().theAnswer("?"))
71 | assertEquals("NOTHING1", Evil().another(1, 2))
72 | }
73 |
74 | @Test
75 | fun simpleTest4() {
76 | every { myDependency.doSomething(anyString()) } returnsAll listOf(
77 | { "test" },
78 | { "TEST" }
79 | )
80 |
81 | val result = sut.myMethod2("myVal")
82 | assertEquals("testTEST", result)
83 |
84 | verifications {
85 | twice { myDependency.doSomething(anyString()) }
86 | never { myDependency.unused() }
87 | }
88 | }
89 |
90 | @Test(expected = RuntimeException::class)
91 | fun simpleTest5() {
92 | every { myDependency.doSomething(anyString()) } answers {
93 | throw RuntimeException()
94 | @Suppress("unreachable_code")
95 | ""
96 | }
97 |
98 | sut.myMethod2("myVal")
99 | }
100 |
101 | @Test
102 | fun simpleTest6() {
103 | every { myDependency.doSomething(argThat { it == "myVal" }) } returns { "test" }
104 |
105 | val result = sut.myMethod2("myVal")
106 | assertEquals("testtest", result)
107 |
108 | verifications {
109 | twice { myDependency.doSomething(anyString()) }
110 | }
111 | }
112 |
113 | @Test
114 | fun simpleTest7() {
115 | every { myDependency.doInt(anyInt()) } returns { 22 }
116 |
117 | val result = sut.myMethodInt(55)
118 | assertEquals(22, result)
119 |
120 | verifications {
121 | once { myDependency.doInt(anyInt()) }
122 | }
123 | }
124 |
125 | @Test
126 | fun simpleTest8() {
127 | every { myDependency.doLong(anyLong()) } returns { 22L }
128 |
129 | val result = sut.myMethodLong(55L)
130 | assertEquals(22L, result)
131 |
132 | verifications {
133 | once { myDependency.doLong(anyLong()) }
134 | }
135 | }
136 |
137 | @Test
138 | fun simpleTest9() {
139 | every { myDependency.doBoolean(anyBoolean()) } returns { false }
140 |
141 | val result = sut.myMethodBoolean(true)
142 | assertEquals(false, result)
143 |
144 | verifications {
145 | once { myDependency.doBoolean(anyBoolean()) }
146 | }
147 | }
148 |
149 | @Test
150 | fun simpleTest10() {
151 | every { myDependency.doChar(anyChar()) } returns { 'x' }
152 |
153 | val result = sut.myMethodChar('a')
154 | assertEquals('x', result)
155 |
156 | verifications {
157 | once { myDependency.doChar(anyChar()) }
158 | }
159 | }
160 |
161 | @Test
162 | fun simpleTest11() {
163 | every { myDependency.doFloat(anyFloat()) } returns { 22.0F }
164 |
165 | val result = sut.myMethodFloat(15F)
166 | assertEquals(22.0F, result, 1F)
167 |
168 | verifications {
169 | once { myDependency.doFloat(anyFloat()) }
170 | }
171 | }
172 |
173 | @Test
174 | fun simpleTest12() {
175 | every { myDependency.doDouble(anyDouble()) } returns { 22.0 }
176 |
177 | val result = sut.myMethodDouble(15.0)
178 | assertEquals(22.0, result, 1.0)
179 |
180 | verifications {
181 | once { myDependency.doDouble(anyDouble()) }
182 | }
183 | }
184 |
185 | @Test
186 | fun simpleTest13() {
187 | every { myDependency.doShort(anyShort()) } returns { 22.toShort() }
188 |
189 | val result = sut.myMethodShort(15.toShort())
190 | assertEquals(22.toShort(), result)
191 |
192 | verifications {
193 | once { myDependency.doShort(anyShort()) }
194 | }
195 | }
196 |
197 | @Test
198 | fun simpleTest14() {
199 | every { myDependency.doByte(anyByte()) } returns { 22.toByte() }
200 |
201 | val result = sut.myMethodByte(15.toByte())
202 | assertEquals(22.toByte(), result)
203 |
204 | verifications {
205 | once { myDependency.doByte(anyByte()) }
206 | }
207 | }
208 |
209 | @Test
210 | fun simpleTest15() {
211 |
212 | mockup {
213 | on(forceFnType<(Evil.(Int) -> String)>(Evil::ambiguous)) {
214 | "1"
215 | }
216 | on(forceFnType<(Evil.(String) -> String)>(Evil::ambiguous)) {
217 | "2"
218 | }
219 | }
220 |
221 | assertEquals("1", Evil().ambiguous(5))
222 | assertEquals("2", Evil().ambiguous("X"))
223 | }
224 |
225 | @Test
226 | fun simpleTest16() {
227 |
228 | mockup {
229 | on(function("ambiguous", Int::class)) {
230 | "1"
231 | }
232 |
233 | on(function("ambiguous", String::class)) {
234 | "2"
235 | }
236 | }
237 |
238 | assertEquals("1", Evil().ambiguous(5))
239 | assertEquals("2", Evil().ambiguous("X"))
240 | }
241 |
242 | @Test
243 | fun simpleTest17() {
244 |
245 | var ctorCalled = false
246 |
247 | mockup {
248 | ctor(String::class) {
249 | ctorCalled = true
250 | }
251 | }
252 |
253 | assertEquals(null, AnotherClass("2").value)
254 | assertTrue(ctorCalled)
255 | }
256 |
257 | @Test
258 | fun simpleTest18() {
259 |
260 | mockupSpecial("de.mobilej.kmockit.SampleCode") {
261 | on(AnotherClass::extension) {
262 | "mocked"
263 | }
264 | }
265 |
266 | assertEquals("mocked", AnotherClass("2").extension(5))
267 | }
268 |
269 | @Test
270 | fun simpleTest19() {
271 |
272 | mockupSpecial("de.mobilej.kmockit.SampleCode") {
273 | on(::topLevel) {
274 | "mocked"
275 | }
276 | }
277 |
278 | assertEquals("mocked", topLevel("Hello"))
279 | }
280 |
281 | @Test
282 | fun simpleTest20() {
283 | every {
284 | myDependency.doSomethingAgain(argThat { it == 5 }, argThat { it == "myVal" })
285 | } returns { "test" }
286 |
287 | val result = sut.myMethod3("myVal")
288 | assertEquals("testtest", result)
289 |
290 | val intHolder = mutableListOf()
291 | val stringHolder = mutableListOf()
292 | verifications {
293 | twice { myDependency.doSomethingAgain(capture(intHolder), capture(stringHolder)) }
294 | }
295 |
296 | assertEquals(2, intHolder.size)
297 | assertEquals(2, stringHolder.size)
298 | }
299 |
300 |
301 | @Test
302 | fun simpleTest21() {
303 | val lambdaHolder = mutableListOf<() -> String>()
304 | sut.myMethod4 { "Hello" }
305 | verifications {
306 | once { myDependency.higherOrderFunction(capture(lambdaHolder)) }
307 | }
308 |
309 | assertEquals("Hello", lambdaHolder[0]())
310 | }
311 |
312 | @Test
313 | fun simpleTest22() {
314 | val lambdaHolder = mutableListOf<(Int, String) -> Long>()
315 | sut.myMethod5 { _, _ -> 21L }
316 | verifications {
317 | once { myDependency.higherOrderFunction2(capture(lambdaHolder)) }
318 | }
319 |
320 | assertEquals(21L, lambdaHolder[0](1, "A"))
321 | }
322 |
323 | @Test
324 | fun simpleTest23() {
325 | val lambdaHolder = mutableListOf<(Int, String) -> Long>()
326 | sut.myMethod6 { _, _ -> 21L }
327 | verifications {
328 | once { myDependency.higherOrderFunction3(argThat { it == 21 }, argThat { it == 42 }, capture(lambdaHolder)) }
329 | }
330 |
331 | assertEquals(21L, lambdaHolder[0](1, "A"))
332 | }
333 | }
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright 2018 Björn Quentin
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
--------------------------------------------------------------------------------
/kmockit/src/main/java/de/mobilej/kmockit/KMockit.kt:
--------------------------------------------------------------------------------
1 | package de.mobilej.kmockit
2 |
3 | import mockit.*
4 | import mockit.integration.junit4.JMockit
5 | import net.bytebuddy.ByteBuddy
6 | import net.bytebuddy.description.annotation.AnnotationDescription
7 | import net.bytebuddy.description.modifier.Visibility
8 | import net.bytebuddy.description.type.TypeDescription
9 | import net.bytebuddy.dynamic.scaffold.subclass.ConstructorStrategy
10 | import net.bytebuddy.implementation.MethodDelegation
11 | import sun.reflect.ReflectionFactory
12 | import java.io.File
13 | import java.lang.reflect.Type
14 | import java.net.URL
15 | import java.net.URLClassLoader
16 | import kotlin.reflect.KClass
17 | import kotlin.reflect.KFunction
18 | import kotlin.reflect.KType
19 | import kotlin.reflect.full.createType
20 | import kotlin.reflect.full.isSubtypeOf
21 | import kotlin.reflect.jvm.javaConstructor
22 | import kotlin.reflect.jvm.javaMethod
23 | import kotlin.reflect.jvm.javaType
24 |
25 |
26 | inline fun delegate(noinline block: (invocation: Invocation) -> T): Delegate {
27 |
28 | val target = object {
29 | @Suppress("unused")
30 | fun answer(invocation: Invocation): T {
31 | return block.invoke(invocation)
32 | }
33 | }
34 |
35 | val generic = TypeDescription.Generic.Builder
36 | .parameterizedType(Delegate::class.java, T::class.java).build()
37 |
38 | val instance = ByteBuddy()
39 | .subclass(generic)
40 | .defineMethod("answer", T::class.java, Visibility.PUBLIC)
41 | .withParameter(TypeDescription.ForLoadedType(Invocation::class.java))
42 | .intercept(MethodDelegation.to(target))
43 | .make()
44 | .load(Delegate::class.java.classLoader)
45 | .getLoaded()
46 | .newInstance()
47 |
48 | @Suppress("unchecked_cast")
49 | return instance as Delegate
50 | }
51 |
52 | // approach found in https://medium.com/@elye.project/befriending-kotlin-and-mockito-1c2e7b0ef791
53 | fun npeAway(what: Any?): T {
54 | return uninitialized(what)
55 | }
56 |
57 | @Suppress("unchecked_cast")
58 | private fun uninitialized(what: Any?): T = what as T
59 |
60 | interface Accessor {
61 | fun any(clazz: Class): T
62 |
63 | fun anyString(): String
64 | fun anyInt(): Int
65 | fun anyBoolean(): Boolean
66 | fun anyChar(): Char
67 | fun anyDouble(): Double
68 | fun anyFloat(): Float
69 | fun anyLong(): Long
70 | fun anyByte(): Byte
71 | fun anyShort(): Short
72 |
73 | fun argThat(retType: KClass<*>, condition: (value: T) -> Boolean): T
74 | }
75 |
76 | interface VerificationAccessor : Accessor {
77 | fun capture(retType: KClass<*>, capturedValues: MutableList): T
78 | }
79 |
80 | class Stubber {
81 | var expect: (Accessor.() -> Unit)? = null
82 |
83 | inline infix fun answers(noinline block: (invocation: Invocation) -> T) {
84 | object : Expectations(), Accessor {
85 | init {
86 | expect?.invoke(this)
87 | result = delegate(block)
88 | }
89 |
90 | override fun any(clazz: Class): T {
91 | return withInstanceOf(clazz)
92 | }
93 |
94 | override fun anyString(): String {
95 | return npeAway(withInstanceOf(String::class.java))
96 | }
97 |
98 | override fun anyInt(): Int {
99 | return withInstanceLike(0)
100 | }
101 |
102 | override fun anyBoolean(): Boolean {
103 | return withInstanceLike(true)
104 | }
105 |
106 | override fun anyByte(): Byte {
107 | return withInstanceLike(0.toByte())
108 | }
109 |
110 | override fun anyChar(): Char {
111 | return withInstanceLike('a')
112 | }
113 |
114 | override fun anyDouble(): Double {
115 | return withInstanceLike(1.0)
116 | }
117 |
118 | override fun anyFloat(): Float {
119 | return withInstanceLike(1.0F)
120 | }
121 |
122 | override fun anyLong(): Long {
123 | return withInstanceLike(0L)
124 | }
125 |
126 | override fun anyShort(): Short {
127 | return withInstanceLike(0.toShort())
128 | }
129 |
130 | override fun argThat(retType: KClass<*>, condition: (value: T) -> Boolean): T {
131 | with(object : Delegate {
132 | @Suppress("unused")
133 | fun match(value: T): Boolean {
134 | return npeAway(condition(value))
135 | }
136 | })
137 | return silentCreate(retType)
138 | }
139 | }
140 | }
141 |
142 | infix fun returns(answer: () -> Any?) {
143 | object : Expectations(), Accessor {
144 | init {
145 | expect?.invoke(this)
146 | result = (answer.invoke())
147 | }
148 |
149 | override fun any(clazz: Class): T {
150 | return withInstanceOf(clazz)
151 | }
152 |
153 | override fun anyString(): String {
154 | return npeAway(withInstanceOf(String::class.java))
155 | }
156 |
157 | override fun anyInt(): Int {
158 | return withInstanceLike(0)
159 | }
160 |
161 | override fun anyBoolean(): Boolean {
162 | return withInstanceLike(true)
163 | }
164 |
165 | override fun anyByte(): Byte {
166 | return withInstanceLike(0.toByte())
167 | }
168 |
169 | override fun anyChar(): Char {
170 | return withInstanceLike('a')
171 | }
172 |
173 | override fun anyDouble(): Double {
174 | return withInstanceLike(1.0)
175 | }
176 |
177 | override fun anyFloat(): Float {
178 | return withInstanceLike(1.0F)
179 | }
180 |
181 | override fun anyLong(): Long {
182 | return withInstanceLike(0L)
183 | }
184 |
185 | override fun anyShort(): Short {
186 | return withInstanceLike(0.toShort())
187 | }
188 |
189 | override fun argThat(retType: KClass<*>, condition: (value: T) -> Boolean): T {
190 | with(object : Delegate {
191 | @Suppress("unused")
192 | fun match(value: T): Boolean {
193 | return npeAway(condition(value))
194 | }
195 | })
196 | return silentCreate(retType)
197 | }
198 | }
199 | }
200 |
201 | infix fun returnsAll(answers: List<() -> Any?>) {
202 | object : Expectations(), Accessor {
203 | init {
204 | expect?.invoke(this)
205 | answers.forEach {
206 | result = (it.invoke())
207 | }
208 | }
209 |
210 | override fun any(clazz: Class): T {
211 | return withInstanceOf(clazz)
212 | }
213 |
214 | override fun anyString(): String {
215 | return npeAway(withInstanceOf(String::class.java))
216 | }
217 |
218 | override fun anyInt(): Int {
219 | return withInstanceLike(0)
220 | }
221 |
222 | override fun anyBoolean(): Boolean {
223 | return withInstanceLike(true)
224 | }
225 |
226 | override fun anyByte(): Byte {
227 | return withInstanceLike(0.toByte())
228 | }
229 |
230 | override fun anyChar(): Char {
231 | return withInstanceLike('a')
232 | }
233 |
234 | override fun anyDouble(): Double {
235 | return withInstanceLike(1.0)
236 | }
237 |
238 | override fun anyFloat(): Float {
239 | return withInstanceLike(1.0F)
240 | }
241 |
242 | override fun anyLong(): Long {
243 | return withInstanceLike(0L)
244 | }
245 |
246 | override fun anyShort(): Short {
247 | return withInstanceLike(0.toShort())
248 | }
249 |
250 | override fun argThat(retType: KClass<*>, condition: (value: T) -> Boolean): T {
251 | with(object : Delegate {
252 | @Suppress("unused")
253 | fun match(value: T): Boolean {
254 | return npeAway(condition(value))
255 | }
256 | })
257 | return silentCreate(retType)
258 | }
259 | }
260 | }
261 |
262 | }
263 |
264 | @Suppress("UNCHECKED_CAST")
265 | fun silentCreate(clazz: KClass<*>): T {
266 |
267 | when (clazz.qualifiedName) {
268 | "kotlin.Function0" -> return { } as T
269 | "kotlin.Function1" -> return { _: Any? -> Unit } as T
270 | "kotlin.Function2" -> return { _: Any?, _: Any? -> Unit } as T
271 | "kotlin.Function3" -> return { _: Any?, _: Any?, _: Any? -> Unit } as T
272 | "kotlin.Function4" -> return { _: Any?, _: Any?, _: Any?, _: Any? -> Unit } as T
273 | "kotlin.Function5" -> return { _: Any?, _: Any?, _: Any?, _: Any?, _: Any? -> Unit } as T
274 | "kotlin.Function6" -> return { _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any? -> Unit } as T
275 | "kotlin.Function7" -> return { _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any? -> Unit } as T
276 | "kotlin.Function8" -> return { _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any? -> Unit } as T
277 | "kotlin.Function9" -> return { _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any? -> Unit } as T
278 | "kotlin.Function10" -> return { _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any? -> Unit } as T
279 | "kotlin.Function11" -> return { _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any? -> Unit } as T
280 | "kotlin.Function12" -> return { _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any? -> Unit } as T
281 | "kotlin.Function13" -> return { _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any? -> Unit } as T
282 | "kotlin.Function14" -> return { _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any? -> Unit } as T
283 | "kotlin.Function15" -> return { _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any? -> Unit } as T
284 | "kotlin.Function16" -> return { _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any? -> Unit } as T
285 | "kotlin.Function17" -> return { _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any? -> Unit } as T
286 | "kotlin.Function18" -> return { _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any? -> Unit } as T
287 | "kotlin.Function19" -> return { _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any? -> Unit } as T
288 | "kotlin.Function20" -> return { _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any?, _: Any? -> Unit } as T
289 | }
290 |
291 | try {
292 | val rf = ReflectionFactory.getReflectionFactory()
293 | val objDef = Object::class.java.getDeclaredConstructor()
294 | val intConstr = rf.newConstructorForSerialization(
295 | clazz.java, objDef
296 | )
297 | return clazz.java.cast(intConstr.newInstance()) as T
298 | } catch (e: RuntimeException) {
299 | throw e
300 | } catch (e: Exception) {
301 | throw IllegalStateException("Cannot create object", e)
302 | }
303 | }
304 |
305 | inline fun Accessor.argThat(noinline condition: (value: T) -> Boolean): T {
306 | return this.argThat(T::class, condition)
307 | }
308 |
309 | inline fun VerificationAccessor.capture(capturedValues: MutableList): T {
310 | return this.capture(T::class, capturedValues)
311 | }
312 |
313 | fun every(block: Accessor.() -> Unit): Stubber {
314 | return Stubber().apply { expect = block }
315 | }
316 |
317 | class VerificationsBlock {
318 | fun times(count: Int, block: VerificationAccessor.() -> Unit) {
319 | object : Verifications(), VerificationAccessor {
320 | init {
321 | block.invoke(this)
322 | times = count
323 | }
324 |
325 | override fun any(clazz: Class): T {
326 | return withInstanceOf(clazz)
327 | }
328 |
329 | override fun anyString(): String {
330 | return npeAway(withInstanceOf(String::class.java))
331 | }
332 |
333 | override fun anyInt(): Int {
334 | return withInstanceLike(0)
335 | }
336 |
337 | override fun anyBoolean(): Boolean {
338 | return withInstanceLike(true)
339 | }
340 |
341 | override fun anyByte(): Byte {
342 | return withInstanceLike(0.toByte())
343 | }
344 |
345 | override fun anyChar(): Char {
346 | return withInstanceLike('a')
347 | }
348 |
349 | override fun anyDouble(): Double {
350 | return withInstanceLike(1.0)
351 | }
352 |
353 | override fun anyFloat(): Float {
354 | return withInstanceLike(1.0F)
355 | }
356 |
357 | override fun anyLong(): Long {
358 | return withInstanceLike(0L)
359 | }
360 |
361 | override fun anyShort(): Short {
362 | return withInstanceLike(0.toShort())
363 | }
364 |
365 | override fun argThat(retType: KClass<*>, condition: (value: T) -> Boolean): T {
366 | with(object : Delegate {
367 | @Suppress("unused")
368 | fun match(value: T): Boolean {
369 | return npeAway(condition(value))
370 | }
371 | })
372 | return silentCreate(retType)
373 | }
374 |
375 | override fun capture(retType: KClass<*>, capturedValues: MutableList): T {
376 | npeAway(withCapture(capturedValues))
377 | return silentCreate(retType)
378 | }
379 |
380 | }
381 | }
382 |
383 | fun once(block: VerificationAccessor.() -> Unit) {
384 | times(1, block)
385 | }
386 |
387 | fun twice(block: VerificationAccessor.() -> Unit) {
388 | times(2, block)
389 | }
390 |
391 | fun never(block: VerificationAccessor.() -> Unit) {
392 | times(0, block)
393 | }
394 | }
395 |
396 | fun verifications(block: VerificationsBlock.() -> Unit) {
397 | block.invoke(VerificationsBlock())
398 | }
399 |
400 | class MockItUp(private val kClass: KClass<*>? = null) {
401 |
402 | val ops = mutableListOf, (Array) -> Any?>>()
403 |
404 | fun on(kFunction1: KFunction<*>, function: (Array) -> R) {
405 | ops.add(Pair(kFunction1, function))
406 | }
407 |
408 | fun ctor(vararg args: KClass<*>, function: (Array) -> R) {
409 | if (kClass == null) {
410 | throw IllegalArgumentException("Ctors not supported here")
411 | }
412 |
413 | val wantedParams = args.map { it.createType() }
414 | val ctor = kClass.constructors.find {
415 | val ptypes = it.parameters.map { it.type }
416 | ptypes == wantedParams
417 | }
418 | if (ctor != null) {
419 | ops.add(Pair(ctor, function))
420 | } else {
421 | throw IllegalArgumentException("No such constructor")
422 | }
423 | }
424 | }
425 |
426 | fun mockupSpecial(ktFile: String, block: MockItUp.() -> Unit) {
427 | val mockItUp = MockItUp()
428 | block(mockItUp)
429 | val toBeMocked = Class.forName("${ktFile}Kt")
430 |
431 | createMockup(mockItUp, toBeMocked, null)
432 | }
433 |
434 | inline fun mockup(block: MockItUp.() -> Unit) {
435 | val mockItUp = MockItUp(T::class)
436 | block(mockItUp)
437 |
438 | createMockup(mockItUp, T::class.java, T::class.createType())
439 | }
440 |
441 | fun createMockup(mockItUp: MockItUp, toBeMocked: Class<*>, toBeMockedType: KType?) {
442 | // collect all methods to be mocked and create a JMockit MockUp dynamically
443 | val generic = TypeDescription.Generic.Builder
444 | .parameterizedType(MockUp::class.java, toBeMocked).build()
445 |
446 | val name = "generatedkmockit.MockUp${System.nanoTime()}"
447 | var bb = ByteBuddy().subclass(generic, ConstructorStrategy.Default.IMITATE_SUPER_CLASS_OPENING)
448 | .name(name)
449 |
450 | mockItUp.ops.forEach { pair ->
451 |
452 | DelegateMethod.add(name, pair.first.javaMethod ?: pair.first.javaConstructor, pair.second)
453 |
454 | val annotation = AnnotationDescription.Builder.ofType(Mock::class.java)
455 | .build()
456 |
457 | var retType: Type = pair.first.returnType.javaType
458 | var methodName = pair.first.name
459 | val paramTypes = pair.first.parameters.filter { toBeMockedType == null || !it.type.isSubtypeOf(toBeMockedType) }.map { it.type.javaType }
460 |
461 | if (methodName == "") {
462 | methodName = "\$init"
463 | retType = Void.TYPE
464 | }
465 |
466 | bb = bb.defineMethod(methodName, retType, Visibility.PUBLIC)
467 | .withParameters(paramTypes)
468 | .intercept(MethodDelegation.to(DelegateMethod::class.java))
469 | .annotateMethod(annotation)
470 | }
471 |
472 |
473 | // need to save it into the classpath - just loading doesn't work for some reason
474 | // this is a bit hacky
475 | val cl = JMockit::class.java.classLoader as URLClassLoader
476 | val intermediatesClasses =
477 | (cl.urLs.find { it.toString().contains("intermediates") && File(it.file).isDirectory && File(it.file).exists() })
478 | ?: (cl.urLs.find { File(it.file).isDirectory })
479 | val classesDir = (intermediatesClasses as URL).file
480 |
481 | cleanUpIfFirstRun(classesDir)
482 |
483 | bb.make()
484 | .saveIn(File(classesDir))
485 |
486 | val clz = Class.forName(name)
487 | clz.newInstance()
488 | }
489 |
490 | fun cleanUpIfFirstRun(directory: String) {
491 | if (firstRun) {
492 | firstRun = false
493 |
494 | File(directory, "generatedkmockit").deleteRecursively()
495 | }
496 | }
497 |
498 | @Suppress("NOTHING_TO_INLINE")
499 | inline fun forceFnType(fn: T) = fn as KFunction<*>
500 |
501 | inline fun function(name: String, vararg args: KClass<*>): KFunction<*> {
502 | val wantedParams = args.map { it.createType() }
503 | val fn = T::class.members.filter {
504 | if (it.name == name) {
505 | val ptypes = it.parameters.map { it.type }.takeLastWhile { it != T::class.createType() }
506 | ptypes == wantedParams
507 | } else {
508 | false
509 | }
510 | }
511 |
512 | if (fn.size != 1 && fn.first() is KFunction<*>) {
513 | throw IllegalArgumentException("No such function found")
514 | } else if (fn.first() !is KFunction<*>) {
515 | throw IllegalArgumentException("No such function found")
516 | }
517 |
518 | return fn.first() as KFunction<*>
519 | }
520 |
521 | private var firstRun = true
--------------------------------------------------------------------------------