├── .travis.yml ├── LICENSE ├── README.md ├── build.gradle.kts ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── publishing.gradle ├── settings.gradle └── src ├── main ├── java │ └── de │ │ └── jodamob │ │ └── junit5 │ │ └── Util.java └── kotlin │ └── de │ └── jodamob │ └── junit5 │ └── SealedClassesSource.kt └── test └── kotlin └── de └── jodamob └── junit5 └── SealedClassesSourceTest.kt /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | jdk: 3 | - openjdk11 4 | 5 | script: 6 | - ./gradlew test 7 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Danny Preussler 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Build Status](https://travis-ci.org/dpreussler/junit5-kotlin.svg?branch=master)](https://travis-ci.org/dpreussler/junit5-kotlin) 2 | 3 | [![Maven Central](https://maven-badges.herokuapp.com/maven-central/de.jodamob.junit5/junit5-kotlin/badge.svg)](https://maven-badges.herokuapp.com/maven-central/de.jodamob.junit5/junit5-kotlin) 4 | [![Jitpack](https://jitpack.io/v/dpreussler/junit5-kotlin.svg)](https://jitpack.io/#dpreussler/junit5-kotlin) 5 | 6 | 7 | # junit5-kotlin 8 | Extensions for Junit5 for Kotlin programming language 9 | 10 | ## SealedClassesSource 11 | Creates instances of sealed classes for `@Parametrized` tests 12 | 13 | Usage: 14 | 15 | ```kotlin 16 | @ParameterizedTest 17 | @SealedClassesSource 18 | fun test(item: SomeClass) 19 | ``` 20 | 21 | Can handle: 22 | - nested sealed classes 23 | - singletons `object` 24 | - empty constructors 25 | - constructors made out of primitive types 26 | 27 | You can pass in a `TypeFactory` for creating custom instances like for mocking 28 | 29 | You can extend the `DefaultTypeFactory` for creating custom instances while reusing the creation of constructors with single paramter constructors with basic types and empty constructors. 30 | 31 | 32 | ```kotlin 33 | sealed class Fruit { 34 | object Orange : Fruit() 35 | object Banana : Fruit() 36 | data class Apple(color: String) : Fruit() 37 | } 38 | 39 | class FruitTypeFactory : DefaultTypeFactory() { 40 | override fun create(what: KClass<*>) = when (what) { 41 | Apple::class -> Fruit.Apple( 42 | color = "red" 43 | ) 44 | else -> super.create(what) 45 | } 46 | } 47 | ``` 48 | 49 | Filter: 50 | 51 | You can filter out a few values by using the names attribute. 52 | 53 | ```kotlin 54 | sealed class Family { 55 | class Mother: Family() 56 | class Father: Family() 57 | sealed class Children: Family() { 58 | class Son: Children() 59 | class Daughter: Children() 60 | sealed class GrandChildren: Children() { 61 | class GrandSon: GrandChildren() 62 | class GradDaughter: GrandChildren() 63 | } 64 | } 65 | } 66 | 67 | @ParameterizedTest 68 | @SealedClassesSource(names = ["Mother", "Daughter", "GrandSon"]) 69 | fun test(item: Family) 70 | ``` 71 | Or you can turn this around by setting the mode attribute to EXCLUDE 72 | 73 | ```kotlin 74 | @ParameterizedTest 75 | @SealedClassesSource(names = ["Mother", "Daughter", "GrandSon"], mode = SealedClassesSource.Mode.EXCLUDE) 76 | fun test(item: Family) 77 | ``` 78 | 79 | Get it: 80 | 81 | ```groovy 82 | dependencies { 83 | implementation 'de.jodamob.junit5:junit5-kotlin:0.0.3' 84 | } 85 | ``` 86 | 87 | 88 | ## License 89 | 90 | 91 | The MIT License (MIT) 92 | 93 | Copyright (c) 2020 Danny Preussler 94 | 95 | Permission is hereby granted, free of charge, to any person obtaining a copy 96 | of this software and associated documentation files (the "Software"), to deal 97 | in the Software without restriction, including without limitation the rights 98 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 99 | copies of the Software, and to permit persons to whom the Software is 100 | furnished to do so, subject to the following conditions: 101 | 102 | The above copyright notice and this permission notice shall be included in all 103 | copies or substantial portions of the Software. 104 | 105 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 106 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 107 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 108 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 109 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 110 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 111 | SOFTWARE. 112 | -------------------------------------------------------------------------------- /build.gradle.kts: -------------------------------------------------------------------------------- 1 | import org.jetbrains.kotlin.gradle.tasks.KotlinCompile 2 | 3 | plugins { 4 | kotlin("jvm") version "1.3.21" 5 | maven 6 | } 7 | 8 | dependencies { 9 | implementation(kotlin("stdlib")) 10 | implementation(kotlin("reflect")) 11 | implementation(junit5("jupiter","5.6.0")) 12 | implementation(junit5("jupiter-params","5.6.0")) 13 | } 14 | 15 | repositories { 16 | jcenter() 17 | } 18 | 19 | group = "berlin.preussler.junit5" 20 | 21 | tasks.withType { 22 | useJUnitPlatform() 23 | } 24 | 25 | // config JVM target to 1.8 for kotlin compilation tasks 26 | tasks.withType().configureEach { 27 | kotlinOptions.jvmTarget = "1.8" 28 | } 29 | 30 | fun DependencyHandler.junit5(module: String, version: String? = null): Any = 31 | "org.junit.jupiter:junit-$module${version?.let { ":$version" } ?: ""}" 32 | 33 | apply(from= "publishing.gradle") 34 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | kotlin.code.style=official 2 | 3 | ossrhUsername= 4 | ossrhPassword= -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dpreussler/junit5-kotlin/a452ab65e40391282d69a23b096ad940b6e58a71/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /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 | # Determine the Java command to use to start the JVM. 86 | if [ -n "$JAVA_HOME" ] ; then 87 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 88 | # IBM's JDK on AIX uses strange locations for the executables 89 | JAVACMD="$JAVA_HOME/jre/sh/java" 90 | else 91 | JAVACMD="$JAVA_HOME/bin/java" 92 | fi 93 | if [ ! -x "$JAVACMD" ] ; then 94 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 95 | 96 | Please set the JAVA_HOME variable in your environment to match the 97 | location of your Java installation." 98 | fi 99 | else 100 | JAVACMD="java" 101 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 102 | 103 | Please set the JAVA_HOME variable in your environment to match the 104 | location of your Java installation." 105 | fi 106 | 107 | # Increase the maximum file descriptors if we can. 108 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 109 | MAX_FD_LIMIT=`ulimit -H -n` 110 | if [ $? -eq 0 ] ; then 111 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 112 | MAX_FD="$MAX_FD_LIMIT" 113 | fi 114 | ulimit -n $MAX_FD 115 | if [ $? -ne 0 ] ; then 116 | warn "Could not set maximum file descriptor limit: $MAX_FD" 117 | fi 118 | else 119 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 120 | fi 121 | fi 122 | 123 | # For Darwin, add options to specify how the application appears in the dock 124 | if $darwin; then 125 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 126 | fi 127 | 128 | # For Cygwin or MSYS, switch paths to Windows format before running java 129 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 130 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 131 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 132 | JAVACMD=`cygpath --unix "$JAVACMD"` 133 | 134 | # We build the pattern for arguments to be converted via cygpath 135 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 136 | SEP="" 137 | for dir in $ROOTDIRSRAW ; do 138 | ROOTDIRS="$ROOTDIRS$SEP$dir" 139 | SEP="|" 140 | done 141 | OURCYGPATTERN="(^($ROOTDIRS))" 142 | # Add a user-defined pattern to the cygpath arguments 143 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 144 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 145 | fi 146 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 147 | i=0 148 | for arg in "$@" ; do 149 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 150 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 151 | 152 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 153 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 154 | else 155 | eval `echo args$i`="\"$arg\"" 156 | fi 157 | i=`expr $i + 1` 158 | done 159 | case $i in 160 | 0) set -- ;; 161 | 1) set -- "$args0" ;; 162 | 2) set -- "$args0" "$args1" ;; 163 | 3) set -- "$args0" "$args1" "$args2" ;; 164 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 165 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 166 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 167 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 168 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 169 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 170 | esac 171 | fi 172 | 173 | # Escape application args 174 | save () { 175 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 176 | echo " " 177 | } 178 | APP_ARGS=`save "$@"` 179 | 180 | # Collect all arguments for the java command, following the shell quoting and substitution rules 181 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 182 | 183 | exec "$JAVACMD" "$@" 184 | -------------------------------------------------------------------------------- /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 Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 33 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 34 | 35 | @rem Find java.exe 36 | if defined JAVA_HOME goto findJavaFromJavaHome 37 | 38 | set JAVA_EXE=java.exe 39 | %JAVA_EXE% -version >NUL 2>&1 40 | if "%ERRORLEVEL%" == "0" goto init 41 | 42 | echo. 43 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 44 | echo. 45 | echo Please set the JAVA_HOME variable in your environment to match the 46 | echo location of your Java installation. 47 | 48 | goto fail 49 | 50 | :findJavaFromJavaHome 51 | set JAVA_HOME=%JAVA_HOME:"=% 52 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 53 | 54 | if exist "%JAVA_EXE%" goto init 55 | 56 | echo. 57 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 58 | echo. 59 | echo Please set the JAVA_HOME variable in your environment to match the 60 | echo location of your Java installation. 61 | 62 | goto fail 63 | 64 | :init 65 | @rem Get command-line arguments, handling Windows variants 66 | 67 | if not "%OS%" == "Windows_NT" goto win9xME_args 68 | 69 | :win9xME_args 70 | @rem Slurp the command line arguments. 71 | set CMD_LINE_ARGS= 72 | set _SKIP=2 73 | 74 | :win9xME_args_slurp 75 | if "x%~1" == "x" goto execute 76 | 77 | set CMD_LINE_ARGS=%* 78 | 79 | :execute 80 | @rem Setup the command line 81 | 82 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 83 | 84 | @rem Execute Gradle 85 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 86 | 87 | :end 88 | @rem End local scope for the variables with windows NT shell 89 | if "%ERRORLEVEL%"=="0" goto mainEnd 90 | 91 | :fail 92 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 93 | rem the _cmd.exe /c_ return code! 94 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 95 | exit /b 1 96 | 97 | :mainEnd 98 | if "%OS%"=="Windows_NT" endlocal 99 | 100 | :omega 101 | -------------------------------------------------------------------------------- /publishing.gradle: -------------------------------------------------------------------------------- 1 | repositories { 2 | mavenCentral() 3 | } 4 | 5 | // Signing 6 | apply plugin: 'signing' 7 | signing { 8 | sign configurations.archives 9 | } 10 | 11 | 12 | // Deploying 13 | apply plugin: 'maven' 14 | 15 | // Add Javadoc JAR and sources JAR to artifact 16 | task javadocJar(type: Jar) { 17 | classifier = 'javadoc' 18 | from javadoc 19 | } 20 | task sourcesJar(type: Jar) { 21 | classifier = 'sources' 22 | from sourceSets.main.allSource 23 | } 24 | artifacts { 25 | archives javadocJar, sourcesJar 26 | } 27 | 28 | // Configure group ID, artifact ID, and version 29 | group = "de.jodamob.junit5" 30 | archivesBaseName = "junit5-kotlin" 31 | version = "0.0.3" 32 | 33 | // Build, sign, and upload 34 | uploadArchives { 35 | repositories { 36 | mavenDeployer { 37 | 38 | // Sign POM 39 | beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) } 40 | 41 | // Destination 42 | repository(url: "https://oss.sonatype.org/service/local/staging/deploy/maven2/") { 43 | authentication(userName: ossrhUsername, password: ossrhPassword) 44 | } 45 | snapshotRepository(url: "https://oss.sonatype.org/content/repositories/snapshots/") { 46 | authentication(userName: ossrhUsername, password: ossrhPassword) 47 | } 48 | 49 | // Add required metadata to POM 50 | pom.project { 51 | name 'junit5-kotlin' 52 | packaging 'jar' 53 | description 'SealedClassesSource for Parameterized tests for Junit5' 54 | url 'https://github.com/dpreussler/junit5-kotlin' 55 | 56 | scm { 57 | connection 'scm:git:git://github.com/dpreussler/junit5-kotlin.git' 58 | developerConnection 'scm:git:ssh://github.com/dpreussler/junit5-kotlin.git' 59 | url 'http://github.com/dpreussler/junit5-kotlin/tree/master' 60 | } 61 | 62 | licenses { 63 | license { 64 | name 'MIT' 65 | url 'https://github.com/dpreussler/junit5-kotlin/blob/master/LICENSE' 66 | } 67 | } 68 | 69 | developers { 70 | developer { 71 | id 'dpreussler' 72 | name 'Danny Preussler' 73 | } 74 | } 75 | } 76 | } 77 | } 78 | } -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'junit5-kotlin' 2 | 3 | -------------------------------------------------------------------------------- /src/main/java/de/jodamob/junit5/Util.java: -------------------------------------------------------------------------------- 1 | package de.jodamob.junit5; 2 | 3 | /* package */ class Util { 4 | @SuppressWarnings("unchecked") 5 | public static Object getEnumConstantByName(Class> enumClass, String name) { 6 | // This is a workaround for KT-5191. Enum#valueOf cannot be called in Kotlin 7 | return Enum.valueOf((Class) enumClass, name); 8 | } 9 | } -------------------------------------------------------------------------------- /src/main/kotlin/de/jodamob/junit5/SealedClassesSource.kt: -------------------------------------------------------------------------------- 1 | package de.jodamob.junit5 2 | 3 | 4 | import org.junit.jupiter.api.extension.ExtensionContext 5 | import org.junit.jupiter.params.provider.Arguments 6 | import org.junit.jupiter.params.provider.ArgumentsProvider 7 | import org.junit.jupiter.params.provider.ArgumentsSource 8 | import org.junit.jupiter.params.support.AnnotationConsumer 9 | import org.junit.platform.commons.util.Preconditions 10 | import java.util.Objects 11 | import kotlin.reflect.* 12 | 13 | /** 14 | * {@code @SealedClassesSource} is an junit ArgumentsSource for sealed classes. 15 | * 16 | *

The sealed class instances will be provided as arguments to the annotated 17 | * {@code @ParameterizedTest} method. 18 | * 19 | * 20 | *

by default only sealed classes with objects or empty constructors are supported, use 21 | * {@link #factoryClass} attribute to provide a factory to create your specific instance. 22 | * 23 | * @see org.junit.jupiter.params.provider.ArgumentsSource 24 | * @see org.junit.jupiter.params.ParameterizedTest 25 | */ 26 | @Target(AnnotationTarget.TYPE, AnnotationTarget.FUNCTION) 27 | @Retention(AnnotationRetention.RUNTIME) 28 | @ArgumentsSource(SealedClassesArgumentsProvider::class) 29 | annotation class SealedClassesSource( 30 | val factoryClass: KClass = DefaultTypeFactory::class, 31 | val names: Array = [], 32 | val mode: Mode = Mode.INCLUDE 33 | ) { 34 | 35 | // factory to create actual instances of a class 36 | interface TypeFactory { 37 | fun create(what: KClass<*>): Any 38 | } 39 | 40 | enum class Mode { 41 | INCLUDE, 42 | EXCLUDE 43 | } 44 | } 45 | 46 | // default factory that can return singletons and instances of classes with empty constructor 47 | open class DefaultTypeFactory: SealedClassesSource.TypeFactory { 48 | 49 | override fun create(what: KClass<*>): Any { 50 | return what.objectInstance ?: what.constructors.first().create() 51 | } 52 | 53 | private fun KFunction.create() = 54 | if (parameters.isEmpty()) call() 55 | else call(*(parameters.map { it.createArgument() }.toTypedArray())) 56 | 57 | // grab known types for constructor arguments 58 | private fun KParameter.createArgument(): Any? { 59 | return type.createArgument() 60 | } 61 | 62 | private fun KType.createArgument(): Any? { 63 | return when (classifier) { 64 | Int::class -> 0 65 | Byte::class -> 0.toByte() 66 | Short::class -> 0.toShort() 67 | String::class -> "" 68 | Float::class -> 0f 69 | Long::class -> 0L 70 | Boolean::class -> false 71 | Throwable::class -> Throwable() 72 | List::class -> emptyList() 73 | Map::class -> emptyMap() 74 | Set::class -> emptySet() 75 | else -> when { 76 | classifier?.isArray() == true -> { 77 | java.lang.reflect.Array.newInstance( 78 | arguments.first().type!!.createArgument()!!.javaClass, 79 | 0 80 | ) 81 | } 82 | classifier?.isEnum() == true -> { 83 | val enumJavaClass = (classifier as KClass>).javaObjectType 84 | Util.getEnumConstantByName( 85 | enumJavaClass, 86 | enumJavaClass.fields.first().name 87 | ) 88 | } 89 | 90 | else -> null 91 | } 92 | } 93 | } 94 | } 95 | 96 | private fun KClassifier.isEnum(): Boolean = (this as KClass<*>).supertypes.any { t -> 97 | (t.classifier as KClass).qualifiedName == "kotlin.Enum" } 98 | 99 | private fun KClassifier.isArray(): Boolean = (this as KClass<*>).qualifiedName == "kotlin.Array" 100 | 101 | 102 | internal class SealedClassesArgumentsProvider : ArgumentsProvider, AnnotationConsumer { 103 | 104 | private lateinit var source: SealedClassesSource 105 | private val factory by lazy { source.factoryClass.java.newInstance() } 106 | 107 | 108 | override fun provideArguments(context: ExtensionContext) = 109 | determineClass(context) 110 | .sealedSubclasses // children 111 | .squashed() // flatten the tree 112 | .filter(source.names, source.mode) 113 | .map { factory.create(it) } // create instances 114 | .map { Arguments.of(it) } // convert to junit arguments 115 | .stream() 116 | 117 | override fun accept(source: SealedClassesSource) { 118 | this.source = source 119 | } 120 | 121 | // flatten a tree and keep only leaves 122 | private fun List>.squashed(): List> = flatMap { 123 | (if (it.sealedSubclasses.isEmpty()) listOf(it) else emptyList()) + it.sealedSubclasses.squashed() 124 | } 125 | 126 | private fun List>.filter( 127 | names: Array, 128 | mode: SealedClassesSource.Mode 129 | ): List> = filter { clazz -> 130 | if (names.isNotEmpty()) { 131 | when (mode) { 132 | SealedClassesSource.Mode.EXCLUDE -> !names.contains(clazz.simpleName) 133 | SealedClassesSource.Mode.INCLUDE -> names.contains(clazz.simpleName) 134 | } 135 | } else { 136 | true 137 | } 138 | } 139 | 140 | 141 | // extracts the class from method parameter, inspired bu org.junit.jupiter.params.provider.EnumArgumentsProvider.determineEnumClass(ExtensionContext) 142 | private fun determineClass(context: ExtensionContext): KClass<*> { 143 | val parameterTypes = context.requiredTestMethod.parameterTypes 144 | Preconditions.condition(parameterTypes.isNotEmpty()) { 145 | "Test method must declare at least one parameter: ${context.requiredTestMethod.toGenericString()}" 146 | } 147 | return parameterTypes[0].kotlin 148 | } 149 | } 150 | -------------------------------------------------------------------------------- /src/test/kotlin/de/jodamob/junit5/SealedClassesSourceTest.kt: -------------------------------------------------------------------------------- 1 | package de.jodamob.junit5 2 | 3 | import org.junit.jupiter.api.AfterAll 4 | import org.junit.jupiter.api.Assertions 5 | import org.junit.jupiter.api.Nested 6 | import org.junit.jupiter.api.TestInstance 7 | import org.junit.jupiter.params.ParameterizedTest 8 | import kotlin.reflect.KClass 9 | 10 | sealed class Letters { 11 | object A: Letters() 12 | object B: Letters() 13 | object C: Letters() 14 | } 15 | 16 | sealed class Family { 17 | class Mother: Family() 18 | class Father: Family() 19 | sealed class Children: Family() { 20 | class Son: Children() 21 | class Daughter: Children() 22 | sealed class GrandChildren: Children() { 23 | class GrandSon: GrandChildren() 24 | class GradDaughter: GrandChildren() 25 | } 26 | } 27 | } 28 | 29 | sealed class Mixed { 30 | data class A(val item: String): Mixed() 31 | data class B(val item: String?): Mixed() 32 | data class C(val item: Int): Mixed() 33 | data class D(val item: Float): Mixed() 34 | data class E(val item: Long): Mixed() 35 | data class F(val item: Short): Mixed() 36 | data class G(val item: Byte): Mixed() 37 | data class H(val item1: String, val item2: Float): Mixed() 38 | data class I(val list: List): Mixed() 39 | data class J(val list: List): Mixed() 40 | data class K(val list: Array): Mixed() 41 | data class L(val map: Set): Mixed() 42 | data class M(val map: Map): Mixed() 43 | 44 | enum class Values{ 45 | VALUE_ONE, VALUE_TWO 46 | } 47 | 48 | data class N(val list: Values): Mixed() 49 | } 50 | 51 | sealed class Custom { 52 | data class YouDontKnowMe(val me: Me): Custom() 53 | class Me 54 | } 55 | 56 | class SealedClassesSourceTest { 57 | 58 | @Nested 59 | @TestInstance(TestInstance.Lifecycle.PER_CLASS) 60 | inner class Singletos { 61 | 62 | val items = mutableListOf() 63 | 64 | @AfterAll 65 | fun check() { 66 | Assertions.assertEquals(listOf("A", "B", "C"), items) 67 | } 68 | 69 | @ParameterizedTest 70 | @SealedClassesSource 71 | fun build(letter: Letters) { 72 | items.add(letter::class.simpleName!!) 73 | } 74 | } 75 | 76 | @Nested 77 | @TestInstance(TestInstance.Lifecycle.PER_CLASS) 78 | inner class Nesting { 79 | 80 | val items = mutableListOf() 81 | 82 | @AfterAll 83 | fun check() { 84 | Assertions.assertEquals(listOf("Mother", "Father", "Son", "Daughter", "GrandSon", "GradDaughter"), items) 85 | } 86 | 87 | @ParameterizedTest 88 | @SealedClassesSource 89 | fun build(member: Family) { 90 | items.add(member::class.simpleName!!) 91 | } 92 | } 93 | 94 | @Nested 95 | @TestInstance(TestInstance.Lifecycle.PER_CLASS) 96 | inner class Constructors { 97 | 98 | val items = mutableListOf() 99 | 100 | @AfterAll 101 | fun check() { 102 | Assertions.assertEquals(listOf("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N"), items) 103 | } 104 | 105 | @ParameterizedTest 106 | @SealedClassesSource 107 | fun build(member: Mixed) { 108 | items.add(member::class.simpleName!!) 109 | } 110 | } 111 | 112 | @Nested 113 | @TestInstance(TestInstance.Lifecycle.PER_CLASS) 114 | inner class Include { 115 | 116 | val items = mutableListOf() 117 | 118 | @AfterAll 119 | fun check() { 120 | Assertions.assertEquals(listOf("Mother", "Daughter", "GrandSon"), items) 121 | } 122 | 123 | @ParameterizedTest 124 | @SealedClassesSource(names = ["Mother", "Daughter", "GrandSon"]) 125 | fun build(member: Family) { 126 | items.add(member::class.simpleName!!) 127 | } 128 | } 129 | 130 | @Nested 131 | @TestInstance(TestInstance.Lifecycle.PER_CLASS) 132 | inner class Exclude { 133 | 134 | val items = mutableListOf() 135 | 136 | @AfterAll 137 | fun check() { 138 | Assertions.assertEquals(listOf("Father", "Son", "GradDaughter"), items) 139 | } 140 | 141 | @ParameterizedTest 142 | @SealedClassesSource( 143 | names = ["Mother", "Daughter", "GrandSon"], 144 | mode = SealedClassesSource.Mode.EXCLUDE 145 | ) 146 | fun build(member: Family) { 147 | items.add(member::class.simpleName!!) 148 | } 149 | } 150 | 151 | @ParameterizedTest 152 | @SealedClassesSource(factoryClass = CustomFactory::class) 153 | fun `can check custom types`(item: Custom) { 154 | Assertions.assertTrue(item is Custom.YouDontKnowMe) 155 | } 156 | 157 | class CustomFactory : SealedClassesSource.TypeFactory { 158 | override fun create(what: KClass<*>) = 159 | Custom.YouDontKnowMe(Custom.Me()) 160 | } 161 | } 162 | --------------------------------------------------------------------------------