diff --git a/MyJUnit2/build.gradle b/MyJUnit2/build.gradle new file mode 100644 index 0000000..fecd564 --- /dev/null +++ b/MyJUnit2/build.gradle @@ -0,0 +1,30 @@ +plugins { + id 'java-library' +} + +dependencies { + compile group: 'com.google.guava', name: 'guava', version: '25.0-jre' + compile group: 'org.jetbrains', name: 'annotations', version: '15.0' + compile group: 'org.projectlombok', name: 'lombok', version: '1.16.20' + compile group: 'commons-io', name: 'commons-io', version: '2.6' + + testCompile group: 'org.hamcrest', name: 'hamcrest-all', version: '1.3' + testCompile group: 'org.junit.jupiter', name: 'junit-jupiter-api', version: '5.1.0' + testCompile group: 'org.junit.jupiter', name: 'junit-jupiter-params', version: '5.0.0-M4' + testCompile group: 'org.mockito', name: 'mockito-all', version: '1.9.5' + + testRuntime group: 'org.junit.jupiter', name: 'junit-jupiter-engine', version: '5.1.0' + testRuntime group: 'org.junit.vintage', name: 'junit-vintage-engine', version: '5.1.0' + + testImplementation group: 'org.junit.jupiter', name: 'junit-jupiter-api', version: '5.1.0' +} + + +repositories { + jcenter() +} + +task wrapper(type: Wrapper) { + description = 'Generates gradlew[.bat] scripts' + gradleVersion = '4.6' +} diff --git a/MyJUnit2/gradle/wrapper/gradle-wrapper.jar b/MyJUnit2/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..91ca28c Binary files /dev/null and b/MyJUnit2/gradle/wrapper/gradle-wrapper.jar differ diff --git a/MyJUnit2/gradle/wrapper/gradle-wrapper.properties b/MyJUnit2/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..84bfd03 --- /dev/null +++ b/MyJUnit2/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Sun May 20 00:25:03 MSK 2018 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-4.7-all.zip diff --git a/MyJUnit2/gradlew b/MyJUnit2/gradlew new file mode 100755 index 0000000..cccdd3d --- /dev/null +++ b/MyJUnit2/gradlew @@ -0,0 +1,172 @@ +#!/usr/bin/env sh + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=$(save "$@") + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong +if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then + cd "$(dirname "$0")" +fi + +exec "$JAVACMD" "$@" diff --git a/MyJUnit2/gradlew.bat b/MyJUnit2/gradlew.bat new file mode 100644 index 0000000..f955316 --- /dev/null +++ b/MyJUnit2/gradlew.bat @@ -0,0 +1,84 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/MyJUnit2/settings.gradle b/MyJUnit2/settings.gradle new file mode 100644 index 0000000..a818a16 --- /dev/null +++ b/MyJUnit2/settings.gradle @@ -0,0 +1,2 @@ +rootProject.name = 'MyJUnit2' + diff --git a/MyJUnit2/src/main/java/Colours.java b/MyJUnit2/src/main/java/Colours.java new file mode 100644 index 0000000..cb86072 --- /dev/null +++ b/MyJUnit2/src/main/java/Colours.java @@ -0,0 +1,23 @@ +/** + * This class is used to create coloured output. One of defined inside colours can be used. + */ +@SuppressWarnings("WeakerAccess") +class Colours { + public static final String ANSI_BLACK = "\u001B[30m"; + public static final String ANSI_RED = "\u001B[31m"; + public static final String ANSI_GREEN = "\u001B[32m"; + public static final String ANSI_YELLOW = "\u001B[33m"; + public static final String ANSI_BLUE = "\u001B[34m"; + public static final String ANSI_PURPLE = "\u001B[35m"; + public static final String ANSI_CYAN = "\u001B[36m"; + public static final String ANSI_WHITE = "\u001B[37m"; + public static final String ANSI_RESET = "\u001B[0m"; + + /** + * The method returns all supported colours. + */ + public static String[] getColours() { + return new String[]{ANSI_BLACK, ANSI_BLUE, ANSI_CYAN, ANSI_RED, + ANSI_RESET, ANSI_GREEN, ANSI_YELLOW, ANSI_WHITE, ANSI_PURPLE}; + } +} diff --git a/MyJUnit2/src/main/java/MethodsCollector.java b/MyJUnit2/src/main/java/MethodsCollector.java new file mode 100644 index 0000000..a840e5e --- /dev/null +++ b/MyJUnit2/src/main/java/MethodsCollector.java @@ -0,0 +1,89 @@ +import annotations.*; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; + +/** + * This class collects methods of given class by groups. + * + * Collects methods for every supported annotation. + */ +@SuppressWarnings("WeakerAccess") +public class MethodsCollector { + + private final Class clazz; + + private final List testCases = new ArrayList<>(); + private final List beforeClassMethods = new ArrayList<>(); + private final List afterClassMethods = new ArrayList<>(); + private final List beforeMethods = new ArrayList<>(); + private final List afterMethods = new ArrayList<>(); + + /** + * Creates new MethodCollector from the given class. Collector will group + * methods of given class by annotation type. + * + * @param clazz class to collect methods from. + */ + public MethodsCollector(final Class clazz) { + this.clazz = clazz; + collectMethods(); + } + + /** + * All methods with {@link Test} annotation. + */ + public List getTestCases() { + return testCases; + } + + /** + * All methods with {@link BeforeClass} annotation. + */ + public List getBeforeClassMethods() { + return beforeClassMethods; + } + + /** + * All methods with {@link AfterClass} annotation. + */ + public List getAfterClassMethods() { + return afterClassMethods; + } + + /** + * All methods with {@link Before} annotation. + */ + public List getBeforeMethods() { + return beforeMethods; + } + + /** + * All methods with {@link After} annotation. + */ + public List getAfterMethods() { + return afterMethods; + } + + private void collectMethods() { + for (final Method method : clazz.getDeclaredMethods()) { + if (method.getAnnotation(Test.class) != null) { + testCases.add(method); + } + if (method.getAnnotation(BeforeClass.class) != null) { + beforeClassMethods.add(method); + } + if (method.getAnnotation(AfterClass.class) != null) { + afterClassMethods.add(method); + } + if (method.getAnnotation(Before.class) != null) { + beforeMethods.add(method); + } + if (method.getAnnotation(After.class) != null) { + afterMethods.add(method); + } + } + } + +} diff --git a/MyJUnit2/src/main/java/MyJUnitLauncher.java b/MyJUnit2/src/main/java/MyJUnitLauncher.java new file mode 100644 index 0000000..7397f01 --- /dev/null +++ b/MyJUnit2/src/main/java/MyJUnitLauncher.java @@ -0,0 +1,174 @@ +import annotations.Test; +import org.jetbrains.annotations.NotNull; + +import java.io.IOException; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.net.URL; +import java.net.URLClassLoader; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; +import java.util.stream.Collectors; + +/** + * The class to run all methods marked with {@link Test} annotation in the target class. + * + * Every testing information will be printed to System.out. + * + * For more information see {@link annotations.After}, {@link annotations.Before}, + * {@link annotations.AfterClass} and {@link annotations.BeforeClass} annotations. + */ +@SuppressWarnings("WeakerAccess") +public class MyJUnitLauncher { + + public static void main(final String[] args) throws IOException, ClassNotFoundException, InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException { + if (args.length != 1) { + System.out.println("Give path to directory with tests as argument"); + return; + } + + testPath(Paths.get(args[0])); + } + + private static void testPath(final Path path) throws IOException, ClassNotFoundException, NoSuchMethodException, + InstantiationException, IllegalAccessException, InvocationTargetException { + for (final Path subPath : Files.walk(path).collect(Collectors.toList())) { + final String name = subPath.getFileName().toString(); + if (name.endsWith(".class")) { + @NotNull final URL url = new URL("file:" + subPath.getParent() + "/"); + @NotNull final ClassLoader classLoader = new URLClassLoader(new URL[]{url}); + final Class clazz = classLoader.loadClass(name.substring(0, name.length() - ".class".length())); + testClass(clazz); + } + } + } + + /** + * Processes testing of given class. + * + * @param clazz class to test. + * @throws InvocationTargetException if any of {@link annotations.After} or {@link annotations.AfterClass} methods + * or class constructor had thrown an exception. + * @throws IllegalAccessException if access to constructor or method was denied. + * @throws NoSuchMethodException if class does not have default constructor. + * @throws InstantiationException if class was abstract. + */ + public static void testClass(final Class clazz) throws + NoSuchMethodException, InstantiationException, InvocationTargetException, IllegalAccessException { + run(clazz); + } + + private static void run(final Class clazz) throws IllegalAccessException, + InstantiationException, NoSuchMethodException, InvocationTargetException { + final Constructor constructor = clazz.getDeclaredConstructor(); + constructor.setAccessible(true); + final Object object = constructor.newInstance(); + + final MyJUnitLogger logger = new MyJUnitLogger(clazz, object); + logger.start(); + + final MethodsCollector collector = new MethodsCollector(clazz); + + try { + processBefore(object, logger, collector); + } catch (final AbortException e) { + logger.finish(); + return; + } + processTests(object, logger, collector); + processAfter(object, logger, collector); + + logger.finish(); + } + + @SuppressWarnings("unused") + private static void processAfter(final Object object, final MyJUnitLogger logger, final MethodsCollector collector) throws InvocationTargetException { + for (final Method method : collector.getAfterClassMethods()) { + method.setAccessible(true); + try { + method.invoke(object); + } catch (final IllegalAccessException e) { + throw new RuntimeException(); + } + } + } + + private static void processBefore(final Object object, final MyJUnitLogger logger, final MethodsCollector collector) throws IllegalAccessException, AbortException { + for (final Method method : collector.getBeforeClassMethods()) { + method.setAccessible(true); + try { + method.invoke(object); + } catch (final InvocationTargetException inv) { + logger.logSetUpFailed(method, inv.getCause()); + throw new AbortException(); + } + } + } + + private static void processBeforeEach(final Object object, final MyJUnitLogger logger, final List methods) throws IllegalAccessException, AbortException { + for (final Method method : methods) { + method.setAccessible(true); + try { + method.invoke(object); + } catch (final InvocationTargetException inv) { + logger.logFailedMethodSetUp(method, inv.getCause()); + throw new AbortException(); + } + } + } + + @SuppressWarnings("unused") + private static void processAfterEach(final Object object, final MyJUnitLogger logger, final List methods) throws IllegalAccessException, InvocationTargetException { + for (final Method method : methods) { + method.setAccessible(true); + method.invoke(object); + } + } + + private static void processTests(final Object object, final MyJUnitLogger logger, final MethodsCollector collector) throws IllegalAccessException, InvocationTargetException { + final List beforeEach = collector.getBeforeMethods(); + final List afterEach = collector.getAfterMethods(); + for (final Method method : collector.getTestCases()) { + final String ignore = method.getAnnotation(Test.class).ignore(); + if (!ignore.equals(Test.NO_IGNORE)) { + logger.logTestSkipped(method, ignore); + continue; + } + + try { + processBeforeEach(object, logger, beforeEach); + } catch (final AbortException e) { + continue; // skip the test + } + + logger.logMethodStart(method); + + method.setAccessible(true); + Throwable t = null; + final Class expected = + method.getAnnotation(Test.class).expected(); + try { + method.invoke(object); + } catch (final InvocationTargetException inv) { + t = inv.getTargetException(); + } + + if (t != null ? t.getClass().equals(expected) : expected == Test.NONE.class) { + logger.logTestPassed(method); + } else { + logger.logTestFailed(method, expected, t == null ? null : t.getClass()); + } + + processAfterEach(object, logger, afterEach); + } + } + + /** + * This exception is used when any exception occurred during Before/After methods. + */ + private static class AbortException extends Throwable { + } +} diff --git a/MyJUnit2/src/main/java/MyJUnitLogger.java b/MyJUnit2/src/main/java/MyJUnitLogger.java new file mode 100644 index 0000000..afb7a03 --- /dev/null +++ b/MyJUnit2/src/main/java/MyJUnitLogger.java @@ -0,0 +1,132 @@ +import annotations.Test; +import com.google.common.base.Stopwatch; +import org.jetbrains.annotations.NotNull; + +import java.lang.reflect.Method; + +/** + * Class with some useful utils to log testing progress. + * + * The class only writing information, it does not invokes tests. + */ +class MyJUnitLogger { + + private final Class clazz; + + private final Stopwatch globalClock = Stopwatch.createUnstarted(); + private final Stopwatch localClock = Stopwatch.createUnstarted(); + private Method calledMethod; + + private int testsPassed; + private int testsSkipped; + private int testsFailed; + + private boolean canceled; + + MyJUnitLogger(final Class clazz, final Object object) { + if (clazz != object.getClass()) { + throw new IllegalArgumentException(); + } + this.clazz = clazz; + } + + void start() { + globalClock.start(); + System.out.println("Running tests for class \"" + + colour(clazz.getName(), Colours.ANSI_BLUE) + "\":"); + printDelimiterLine(); + } + + void finish() { + globalClock.stop(); + if (canceled) { + System.out.println("Testing was canceled."); + return; + } + System.out.println("Testing finished in " + globalClock); + System.out.println("Failed tests number: " + testsFailed); + System.out.println("Skipped tests number: " + testsSkipped); + System.out.print("Passed tests number: " + testsPassed); + } + + void logMethodStart(final Method method) { + calledMethod = method; + localClock.reset(); + localClock.start(); + + System.out.println("Starting test \"" + + colour(method.getName(), Colours.ANSI_BLUE) + "\""); + } + + void logTestPassed(final Method method) { + testsPassed++; + assert(method == calledMethod); + localClock.stop(); + System.out.println("Test \"" + colour(method.getName(), Colours.ANSI_BLUE) + + "\" passed in " + localClock + " | Verdict: " + + colour("OK", Colours.ANSI_GREEN)); + printDelimiterLine(); + calledMethod = null; + } + + void logTestSkipped(@NotNull final Method method, final String reason) { + testsSkipped++; + System.out.println("Test \"" + colour(method.getName(), Colours.ANSI_BLUE) + + "\" skipped in " + localClock + " | Verdict: " + + colour("SKIPPED", Colours.ANSI_YELLOW)); + System.out.println("Reason: \"" + reason + "\""); + printDelimiterLine(); + calledMethod = null; + } + + void logTestFailed(final Method method, final Class expected, final Class gotten) { + testsFailed++; + assert(method == calledMethod); + localClock.stop(); + System.out.println("Test \"" + colour(method.getName(), Colours.ANSI_BLUE) + + "\" failed in " + localClock + " | Verdict: " + + colour("FAILED", Colours.ANSI_RED)); + final String gottenString = gotten == null ? Test.NONE.class.getName() : gotten.getName(); + System.out.println(colour("Excpected exception type is " + expected.getName() + + " but was " + gottenString, Colours.ANSI_RED)); + printDelimiterLine(); + calledMethod = null; + } + + void logFailedMethodSetUp(final Method method, final Throwable cause) { + System.out.println("Set up was failed for method: " + + colour(method.getName(), Colours.ANSI_BLUE) + " with exception"); + cause.printStackTrace(); + System.out.println("Test will b counted as failed."); + cancel(); + } + + void logFailedMethodTearDown(final Method method, final Throwable cause) { + System.out.println("Tear down failed for method: " + + colour(method.getName(), Colours.ANSI_BLUE) + " with exception"); + cause.printStackTrace(); + System.out.println("Test will b counted as failed."); + cancel(); + } + + void logSetUpFailed(final Method method, final Throwable cause) { + System.out.println("Exception occurred in while setting up in method " + + colour(method.getName(), Colours.ANSI_BLUE) + ". Testing will be stopped"); + cause.printStackTrace(); + printDelimiterLine(); + canceled = true; + } + + private void cancel() { + localClock.stop(); + calledMethod = null; + } + + private void printDelimiterLine() { + System.out.println("---------------------------------------------------------------------------"); + } + + private String colour(final String s, final String colour) { + return colour + s + Colours.ANSI_RESET; + } +} diff --git a/MyJUnit2/src/main/java/annotations/After.java b/MyJUnit2/src/main/java/annotations/After.java new file mode 100644 index 0000000..ab8d7a0 --- /dev/null +++ b/MyJUnit2/src/main/java/annotations/After.java @@ -0,0 +1,16 @@ +package annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * This annotation is used to show, that method must be invoked after every test. + * + * Invocation order might be not guaranteed. + */ +@Target({ElementType.METHOD}) +@Retention(RetentionPolicy.RUNTIME) +public @interface After { +} diff --git a/MyJUnit2/src/main/java/annotations/AfterClass.java b/MyJUnit2/src/main/java/annotations/AfterClass.java new file mode 100644 index 0000000..231588f --- /dev/null +++ b/MyJUnit2/src/main/java/annotations/AfterClass.java @@ -0,0 +1,16 @@ +package annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * This annotation is used to show, that method must be invoked after testing class. + * + * Invocation order might be not guaranteed. + */ +@Target({ElementType.METHOD}) +@Retention(RetentionPolicy.RUNTIME) +public @interface AfterClass { +} diff --git a/MyJUnit2/src/main/java/annotations/Before.java b/MyJUnit2/src/main/java/annotations/Before.java new file mode 100644 index 0000000..8f3703e --- /dev/null +++ b/MyJUnit2/src/main/java/annotations/Before.java @@ -0,0 +1,16 @@ +package annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * This annotation is used to show, that method must be invoked before every test. + * + * Invocation order might be not guaranteed. + */ +@Target({ElementType.METHOD}) +@Retention(RetentionPolicy.RUNTIME) +public @interface Before { +} diff --git a/MyJUnit2/src/main/java/annotations/BeforeClass.java b/MyJUnit2/src/main/java/annotations/BeforeClass.java new file mode 100644 index 0000000..5d5bb4c --- /dev/null +++ b/MyJUnit2/src/main/java/annotations/BeforeClass.java @@ -0,0 +1,16 @@ +package annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * This annotation is used to show, that method must be invoked before testing class. + * + * Invocation order might be not guaranteed. + */ +@Target({ElementType.METHOD}) +@Retention(RetentionPolicy.RUNTIME) +public @interface BeforeClass { +} diff --git a/MyJUnit2/src/main/java/annotations/Test.java b/MyJUnit2/src/main/java/annotations/Test.java new file mode 100644 index 0000000..882f239 --- /dev/null +++ b/MyJUnit2/src/main/java/annotations/Test.java @@ -0,0 +1,32 @@ +package annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * This annotation is used to mark methods, that must be invoked as tests. + * + * If {@link Test#ignore()} argument is set and equals to something else then "NO_IGNORE", + * method invocation will be skipped with reason written in {@link Test#ignore()} argument. + * + * If {@link Test#expected()} argument is set to any exception test invocation will expect + * {@link Test#expected()} exception to be thrown. If no exception was thrown, or exception + * class was not the target one, test will be counted as failed. + * + * If no {@link Test#expected()} was provided test will be counted as failed in case if + * any exception was thrown. + */ +@Target({ElementType.METHOD}) +@Retention(RetentionPolicy.RUNTIME) +public @interface Test { + + String NO_IGNORE = "NO_IGNORE"; + + String ignore() default NO_IGNORE; + + Class expected() default NONE.class; + + class NONE extends Throwable {} +} diff --git a/MyJUnit2/src/test/java/Cause.java b/MyJUnit2/src/test/java/Cause.java new file mode 100644 index 0000000..a293644 --- /dev/null +++ b/MyJUnit2/src/test/java/Cause.java @@ -0,0 +1,18 @@ +class Cause { + + private final Class expected; + private final Class was; + + Cause(final Class expected, final Class was) { + this.expected = expected; + this.was = was; + } + + Class expected() { + return expected; + } + + Class was() { + return was; + } +} diff --git a/MyJUnit2/src/test/java/GeneralTest.java b/MyJUnit2/src/test/java/GeneralTest.java new file mode 100644 index 0000000..9948fbd --- /dev/null +++ b/MyJUnit2/src/test/java/GeneralTest.java @@ -0,0 +1,110 @@ +import annotations.Test; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.lang.reflect.InvocationTargetException; +import java.util.Set; +import java.util.TreeSet; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.startsWith; +import static org.hamcrest.core.Is.is; + +@SuppressWarnings("WeakerAccess") +public class GeneralTest { + + static void testClass(final Class clazz, final TestResults results) + throws InvocationTargetException, IllegalAccessException, NoSuchMethodException, InstantiationException { + final ByteArrayOutputStream os = new ByteArrayOutputStream(); + + final PrintStream old = System.out; + System.setOut(new PrintStream(os)); + + MyJUnitLauncher.testClass(clazz); + + final String result = os.toString(); + final String[] lines = result.split("\n"); + + System.setOut(old); + for (final String line : lines) { + System.out.println(line); + } + + removeColours(lines); + + checkPassed(lines, results); + checkFailed(lines, results); + checkSkipped(lines, results); + checkResults(lines, results); + checkGeneral(lines, results); + + + assertThat(lines.length, is(results.testsPassed().size() * 3 + + results.testsSkipped().size() * 3 + results.testsFailed().size() * 4 + 6)); + } + + private static void checkSkipped(final String[] lines, final TestResults results) { + final Set skipped = new TreeSet<>(); + for (int i = 1; i < lines.length - 5; i++) { + if (lines[i].endsWith("SKIPPED")) { + final String testName = lines[i].split("\"")[1]; + final String printedReason = lines[i + 1].substring(9, lines[i + 1].length() - 1); + skipped.add(testName); + + final String expectedReason = results.testsSkipped().get(testName); + assertThat(printedReason, is(expectedReason)); + + i++; + } + } + assertThat(skipped, is(results.testsSkipped().keySet())); + } + + private static void checkFailed(final String[] lines, final TestResults results) { + final Set failed = new TreeSet<>(); + for (int i = 1; i < lines.length - 5; i++) { + if (lines[i].endsWith("FAILED")) { + final String testName = lines[i].split("\"")[1]; + final String expected = lines[i + 1].split(" ")[4]; + final String was = lines[i + 1].split(" ")[7]; + failed.add(testName); + + final Class gottenRes = results.testsFailed().get(testName).was(); + assertThat(expected, is(results.testsFailed().get(testName).expected().getName())); + assertThat(was, is(gottenRes == null ? Test.NONE.class.getName() : gottenRes.getName())); + + i++; + } + } + assertThat(failed, is(results.testsFailed().keySet())); + } + + private static void checkPassed(final String[] lines, final TestResults results) { + final Set accepted = new TreeSet<>(); + for (int i = 1; i < lines.length - 5; i++) { + if (lines[i].endsWith("OK")) { + accepted.add(lines[i].split("\"")[1]); + } + } + assertThat(accepted, is(results.testsPassed())); + } + + private static void checkResults(final String[] lines, final TestResults results) { + assertThat(lines[lines.length - 3], is("Failed tests number: " + results.testsFailed().size())); + assertThat(lines[lines.length - 2], is("Skipped tests number: " + results.testsSkipped().size())); + assertThat(lines[lines.length - 1], is("Passed tests number: " + results.testsPassed().size())); + } + + private static void checkGeneral(final String[] lines, final TestResults results) { + assertThat(lines[0], is("Running tests for class \"" + results.className() + "\":")); + assertThat(lines[lines.length - 4], startsWith("Testing finished in ")); + } + + private static void removeColours(final String[] lines) { + for (int i = 0; i < lines.length; i++) { + for (final String colour : Colours.getColours()) { + lines[i] = lines[i].replace(colour, ""); + } + } + } +} diff --git a/MyJUnit2/src/test/java/MyJUnitLauncherTest.java b/MyJUnit2/src/test/java/MyJUnitLauncherTest.java new file mode 100644 index 0000000..a08b1d1 --- /dev/null +++ b/MyJUnit2/src/test/java/MyJUnitLauncherTest.java @@ -0,0 +1,273 @@ +import org.junit.jupiter.api.Test; +import testCases.beforeAndAfter.AfterMethod; +import testCases.beforeAndAfter.AfterPrivateAccess; +import testCases.beforeAndAfter.BeforeMethod; +import testCases.beforeAndAfter.BeforePrivateAccess; +import testCases.beforeAndAfterClass.AfterClassMethod; +import testCases.beforeAndAfterClass.BeforeAndAfterClassMethod; +import testCases.beforeAndAfterClass.BeforeClassMethod; +import testCases.beforeAndAfterClass.BeforeAndAfterClassPrivateAccess; +import testCases.exceptions.*; +import testCases.base.*; +import testCases.other.Modifiers; +import testCases.other.PrivateConstructor; +import testCases.other.StaticModifier; +import testCases.skip.*; + +import java.lang.reflect.InvocationTargetException; +import java.util.Collections; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.Is.is; + +class MyJUnitLauncherTest { + + private static final Class none = annotations.Test.NONE.class; + + @Test + void testEmpty() throws InvocationTargetException, IllegalAccessException, NoSuchMethodException, + InstantiationException { + GeneralTest.testClass(Empty.class, + new TestResults(Empty.class.getName(), Collections.emptyMap(), + Collections.emptyMap(), Collections.emptySet())); + } + + @Test + void testOneTest() throws InvocationTargetException, IllegalAccessException, NoSuchMethodException, + InstantiationException { + GeneralTest.testClass(OneTest.class, + new TestResults(OneTest.class.getName(), Collections.emptyMap(), + Collections.emptyMap(), Collections.singleton("bar"))); + } + + @Test + void testMixedMethods() throws InvocationTargetException, IllegalAccessException, NoSuchMethodException, + InstantiationException { + GeneralTest.testClass(MixedMethods.class, + new TestResults(MixedMethods.class.getName(), Collections.emptyMap(), + Collections.emptyMap(), Utils.set("foo", "bar"))); + } + + @Test + void testTwoTests() throws InvocationTargetException, IllegalAccessException, NoSuchMethodException, + InstantiationException { + GeneralTest.testClass(TwoTests.class, + new TestResults(TwoTests.class.getName(), Collections.emptyMap(), + Collections.emptyMap(), Utils.set("foo", "bar"))); + } + + @Test + void testWithoutTestAnnotations() throws InvocationTargetException, IllegalAccessException, NoSuchMethodException, InstantiationException { + GeneralTest.testClass(WithoutTestAnnotations.class, + new TestResults(WithoutTestAnnotations.class.getName(), + Collections.emptyMap(), Collections.emptyMap(), + Collections.emptySet())); + } + + @Test + void testStaticModifier() throws InvocationTargetException, IllegalAccessException, NoSuchMethodException, + InstantiationException { + GeneralTest.testClass(StaticModifier.class, + new TestResults(StaticModifier.class.getName(), + Collections.emptyMap(), Collections.emptyMap(), + Utils.set("publicMethod", "protectedMethod", + "privateMethod", "defaultMethod"))); + } + + @Test + void testModifiers() throws InvocationTargetException, IllegalAccessException, NoSuchMethodException, + InstantiationException { + GeneralTest.testClass(Modifiers.class, + new TestResults(Modifiers.class.getName(), + Collections.emptyMap(), Collections.emptyMap(), + Utils.set("publicMethod", "protectedMethod", + "privateMethod", "defaultMethod"))); + } + + @Test + void testPrivateConstructor() throws InvocationTargetException, IllegalAccessException, NoSuchMethodException, + InstantiationException { + GeneralTest.testClass(PrivateConstructor.class, + new TestResults(PrivateConstructor.class.getName(), + Collections.emptyMap(), Collections.emptyMap(), + Utils.set("test"))); + } + + @Test + void testUnsupposedException() throws InvocationTargetException, IllegalAccessException, NoSuchMethodException, + InstantiationException { + GeneralTest.testClass(UnsupposedException.class, + new TestResults(UnsupposedException.class.getName(), + Utils.makeFailedMap("failed", none, ArithmeticException.class), + Collections.emptyMap(), Utils.set("good"))); + } + + @Test + void testWrongException() throws InvocationTargetException, IllegalAccessException, NoSuchMethodException, + InstantiationException { + GeneralTest.testClass(WrongException.class, + new TestResults(WrongException.class.getName(), + Utils.makeFailedMap("failed", ArithmeticException.class, NullPointerException.class), + Collections.emptyMap(), Collections.emptySet())); + } + + @Test + void testCorrectException() throws InvocationTargetException, IllegalAccessException, NoSuchMethodException, + InstantiationException { + GeneralTest.testClass(CorrectException.class, + new TestResults(CorrectException.class.getName(), Collections.emptyMap(), + Collections.emptyMap(), Utils.set("good"))); + } + + @Test + void testMoreFailing() throws InvocationTargetException, IllegalAccessException, NoSuchMethodException, + InstantiationException { + GeneralTest.testClass(MoreFailing.class, + new TestResults(MoreFailing.class.getName(), + Utils.makeFailedMap("failedNone", none, NullPointerException.class, + "failedWrong", ArithmeticException.class, NullPointerException.class), + Collections.emptyMap(), Collections.emptySet())); + } + + @Test + void testNoExceptionGotten() throws InvocationTargetException, IllegalAccessException, NoSuchMethodException, + InstantiationException { + GeneralTest.testClass(NoExceptionGotten.class, + new TestResults(NoExceptionGotten.class.getName(), + Utils.makeFailedMap("empty", ArithmeticException.class, null), + Collections.emptyMap(), Collections.emptySet())); + } + + @Test + void testTestIgnoreOne() throws InvocationTargetException, IllegalAccessException, NoSuchMethodException, + InstantiationException { + GeneralTest.testClass(IgnoreOne.class, + new TestResults(IgnoreOne.class.getName(), + Collections.emptyMap(), + Utils.makeSkippedMap("skipTest", "reason"), + Collections.emptySet())); + } + + @Test + void testTestIgnoreEmpty() throws InvocationTargetException, IllegalAccessException, NoSuchMethodException, + InstantiationException { + GeneralTest.testClass(IgnoreEmpty.class, + new TestResults(IgnoreEmpty.class.getName(), + Collections.emptyMap(), + Utils.makeSkippedMap("skipTest", ""), + Collections.emptySet())); + } + + @Test + void testTestIgnoreTwo() throws InvocationTargetException, IllegalAccessException, NoSuchMethodException, + InstantiationException { + GeneralTest.testClass(IgnoreTwo.class, + new TestResults(IgnoreTwo.class.getName(), + Collections.emptyMap(), + Utils.makeSkippedMap("skipTest2", "reason2", "skipTest1", "reason1"), + Collections.emptySet())); + } + + @Test + void testIgnoreWithRegular() throws InvocationTargetException, IllegalAccessException, NoSuchMethodException, + InstantiationException { + GeneralTest.testClass(IgnoreWithRegular.class, + new TestResults(IgnoreWithRegular.class.getName(), + Collections.emptyMap(), + Utils.makeSkippedMap("skipTest", "reason"), + Utils.set("passedTest"))); + } + + @Test + void testIgnoreWithFailed() throws InvocationTargetException, IllegalAccessException, NoSuchMethodException, + InstantiationException { + GeneralTest.testClass(IgnoreWithFailed.class, + new TestResults(IgnoreWithFailed.class.getName(), + Utils.makeFailedMap("failedTest", RuntimeException.class, null), + Utils.makeSkippedMap("skipTest", "reason"), + Collections.emptySet())); + } + + @Test + void testIgnoreFullMix() throws InvocationTargetException, IllegalAccessException, NoSuchMethodException, + InstantiationException { + GeneralTest.testClass(IgnoreFullMix.class, + new TestResults(IgnoreFullMix.class.getName(), + Utils.makeFailedMap("failedTest", RuntimeException.class, null), + Utils.makeSkippedMap("skipTest", "reason"), + Utils.set("passedTest"))); + } + + @Test + void testAfterClassMethod() throws InvocationTargetException, IllegalAccessException, NoSuchMethodException, + InstantiationException { + GeneralTest.testClass(AfterClassMethod.class, + new TestResults(AfterClassMethod.class.getName(), Collections.emptyMap(), + Collections.emptyMap(), Utils.set("test"))); + assertThat(AfterClassMethod.x(), is(1)); + } + + @Test + void testBeforeClassMethod() throws InvocationTargetException, IllegalAccessException, NoSuchMethodException, + InstantiationException { + GeneralTest.testClass(BeforeClassMethod.class, + new TestResults(BeforeClassMethod.class.getName(), Collections.emptyMap(), + Collections.emptyMap(), Utils.set("test"))); + assertThat(BeforeClassMethod.x(), is(1)); + } + + @Test + void testBeforeAndAfterClassMethod() throws InvocationTargetException, IllegalAccessException, NoSuchMethodException, + InstantiationException { + GeneralTest.testClass(BeforeAndAfterClassMethod.class, + new TestResults(BeforeAndAfterClassMethod.class.getName(), Collections.emptyMap(), + Collections.emptyMap(), Utils.set("test"))); + assertThat(BeforeAndAfterClassMethod.x(), is(1)); + } + + @Test + void testPrivateAccess() throws InvocationTargetException, IllegalAccessException, NoSuchMethodException, + InstantiationException { + GeneralTest.testClass(BeforeAndAfterClassPrivateAccess.class, + new TestResults(BeforeAndAfterClassPrivateAccess.class.getName(), Collections.emptyMap(), + Collections.emptyMap(), Utils.set("test"))); + assertThat(BeforeAndAfterClassMethod.x(), is(1)); + } + + @Test + void testBeforeMethod() throws InvocationTargetException, IllegalAccessException, NoSuchMethodException, + InstantiationException { + GeneralTest.testClass(BeforeMethod.class, + new TestResults(BeforeMethod.class.getName(), Collections.emptyMap(), + Collections.emptyMap(), Utils.set("test1", "test2"))); + assertThat(BeforeMethod.x(), is(0)); + } + + @Test + void testAfterMethod() throws InvocationTargetException, IllegalAccessException, NoSuchMethodException, + InstantiationException { + GeneralTest.testClass(AfterMethod.class, + new TestResults(AfterMethod.class.getName(), Collections.emptyMap(), + Collections.emptyMap(), Utils.set("test1", "test2", "test3"))); + assertThat(AfterMethod.x(), is(1)); + } + + @Test + void testAfterPrivateAccess() throws InvocationTargetException, IllegalAccessException, NoSuchMethodException, + InstantiationException { + GeneralTest.testClass(AfterPrivateAccess.class, + new TestResults(AfterPrivateAccess.class.getName(), Collections.emptyMap(), + Collections.emptyMap(), Utils.set("test1", "test2"))); + assertThat(AfterPrivateAccess.x(), is(1)); + } + + @Test + void testBeforePrivateAccess() throws InvocationTargetException, IllegalAccessException, NoSuchMethodException, + InstantiationException { + GeneralTest.testClass(BeforePrivateAccess.class, + new TestResults(BeforePrivateAccess.class.getName(), Collections.emptyMap(), + Collections.emptyMap(), Utils.set("test"))); + assertThat(BeforePrivateAccess.x(), is(0)); + } + +} \ No newline at end of file diff --git a/MyJUnit2/src/test/java/TestResults.java b/MyJUnit2/src/test/java/TestResults.java new file mode 100644 index 0000000..6b5ebac --- /dev/null +++ b/MyJUnit2/src/test/java/TestResults.java @@ -0,0 +1,45 @@ +import java.util.Map; +import java.util.Set; + +@SuppressWarnings("WeakerAccess") +public class TestResults { + + private final String className; + private final Map testsFailed; + private final Map testsSkipped; + private final Set testsPassed; + private final int testsStarted; + + TestResults(final String className, + final Map failedTests, + final Map skippedTests, + final Set passedTests) { + + this.className = className; + testsSkipped = skippedTests; + testsFailed = failedTests; + testsPassed = passedTests; + testsStarted = testsFailed.size() + testsPassed.size(); + } + + public String className() { + return className; + } + + public Map testsFailed() { + return testsFailed; + } + + public Map testsSkipped() { + return testsSkipped; + } + + public Set testsPassed() { + return testsPassed; + } + + public int testsStarted() { + return testsStarted; + } + +} diff --git a/MyJUnit2/src/test/java/Utils.java b/MyJUnit2/src/test/java/Utils.java new file mode 100644 index 0000000..4314239 --- /dev/null +++ b/MyJUnit2/src/test/java/Utils.java @@ -0,0 +1,29 @@ +import java.util.*; + +class Utils { + + @SafeVarargs + static Set set(final T... elements) { + return new TreeSet<>(Arrays.asList(elements)); + } + + @SuppressWarnings("unchecked") + static Map makeFailedMap(final Object... args) { + final Map map = new TreeMap<>(); + for (int i = 0; i < args.length; i += 3) { + map.put((String) args[i], + new Cause((Class)args[i + 1], + (Class) args[i + 2])); + } + return map; + } + + static Map makeSkippedMap(final String... args) { + final Map map = new TreeMap<>(); + for (int i = 0; i < args.length; i += 2) { + map.put(args[i], args[i + 1]); + } + return map; + } + +} diff --git a/MyJUnit2/src/test/java/testCases/base/Empty.java b/MyJUnit2/src/test/java/testCases/base/Empty.java new file mode 100644 index 0000000..43f6b61 --- /dev/null +++ b/MyJUnit2/src/test/java/testCases/base/Empty.java @@ -0,0 +1,5 @@ +package testCases.base; + +public class Empty { + +} diff --git a/MyJUnit2/src/test/java/testCases/base/MixedMethods.java b/MyJUnit2/src/test/java/testCases/base/MixedMethods.java new file mode 100644 index 0000000..623701a --- /dev/null +++ b/MyJUnit2/src/test/java/testCases/base/MixedMethods.java @@ -0,0 +1,15 @@ +package testCases.base; + +import annotations.Test; + +public class MixedMethods { + + @Test + void foo() {} + + @Test + void bar() {} + + void baz() {} + +} diff --git a/MyJUnit2/src/test/java/testCases/base/OneTest.java b/MyJUnit2/src/test/java/testCases/base/OneTest.java new file mode 100644 index 0000000..679db27 --- /dev/null +++ b/MyJUnit2/src/test/java/testCases/base/OneTest.java @@ -0,0 +1,12 @@ +package testCases.base; + +import annotations.Test; + +public class OneTest { + + @Test + void bar() { + + } + +} diff --git a/MyJUnit2/src/test/java/testCases/base/TwoTests.java b/MyJUnit2/src/test/java/testCases/base/TwoTests.java new file mode 100644 index 0000000..3763e66 --- /dev/null +++ b/MyJUnit2/src/test/java/testCases/base/TwoTests.java @@ -0,0 +1,13 @@ +package testCases.base; + +import annotations.Test; + +public class TwoTests { + + @Test + void foo() {} + + @Test + void bar() {} + +} diff --git a/MyJUnit2/src/test/java/testCases/base/WithoutTestAnnotations.java b/MyJUnit2/src/test/java/testCases/base/WithoutTestAnnotations.java new file mode 100644 index 0000000..5c8f7ef --- /dev/null +++ b/MyJUnit2/src/test/java/testCases/base/WithoutTestAnnotations.java @@ -0,0 +1,10 @@ +package testCases.base; + +public class WithoutTestAnnotations { + + public void foo() {} + + public void bar() {} + + public String baz() { return null; } +} diff --git a/MyJUnit2/src/test/java/testCases/beforeAndAfter/AfterMethod.java b/MyJUnit2/src/test/java/testCases/beforeAndAfter/AfterMethod.java new file mode 100644 index 0000000..2ddee19 --- /dev/null +++ b/MyJUnit2/src/test/java/testCases/beforeAndAfter/AfterMethod.java @@ -0,0 +1,42 @@ +package testCases.beforeAndAfter; + +import annotations.After; +import annotations.Test; + +public class AfterMethod { + + private static int x = 1; + + @After + public void after() { + x = 1; + } + + @Test + public void test1() { + if (x != 1) { + throw new RuntimeException(); + } + x = 0; + } + + @Test + public void test2() { + if (x != 1) { + throw new RuntimeException(); + } + x = 0; + } + + @Test + public void test3() { + if (x != 1) { + throw new RuntimeException(); + } + x = 0; + } + + public static int x() { + return x; + } +} diff --git a/MyJUnit2/src/test/java/testCases/beforeAndAfter/AfterPrivateAccess.java b/MyJUnit2/src/test/java/testCases/beforeAndAfter/AfterPrivateAccess.java new file mode 100644 index 0000000..ae04d7b --- /dev/null +++ b/MyJUnit2/src/test/java/testCases/beforeAndAfter/AfterPrivateAccess.java @@ -0,0 +1,34 @@ +package testCases.beforeAndAfter; + +import annotations.After; +import annotations.Test; + +public class AfterPrivateAccess { + + private static int x = 1; + + @After + private void before() { + x = 1; + } + + @Test + public void test1() { + if (x != 1) { + throw new RuntimeException(); + } + x = 0; + } + + @Test + public void test2() { + if (x != 1) { + throw new RuntimeException(); + } + x = 0; + } + + public static int x() { + return x; + } +} diff --git a/MyJUnit2/src/test/java/testCases/beforeAndAfter/BeforeMethod.java b/MyJUnit2/src/test/java/testCases/beforeAndAfter/BeforeMethod.java new file mode 100644 index 0000000..ada169c --- /dev/null +++ b/MyJUnit2/src/test/java/testCases/beforeAndAfter/BeforeMethod.java @@ -0,0 +1,35 @@ +package testCases.beforeAndAfter; + +import annotations.Before; +import annotations.Test; + +public class BeforeMethod { + + private static int x = 0; + + @Before + public void before() { + x = 1; + } + + @Test + public void test1() { + if (x != 1) { + throw new RuntimeException(); + } + x = 0; + } + + @Test + public void test2() { + if (x != 1) { + throw new RuntimeException(); + } + x = 0; + } + + public static int x() { + return x; + } + +} diff --git a/MyJUnit2/src/test/java/testCases/beforeAndAfter/BeforePrivateAccess.java b/MyJUnit2/src/test/java/testCases/beforeAndAfter/BeforePrivateAccess.java new file mode 100644 index 0000000..f47e32b --- /dev/null +++ b/MyJUnit2/src/test/java/testCases/beforeAndAfter/BeforePrivateAccess.java @@ -0,0 +1,26 @@ +package testCases.beforeAndAfter; + +import annotations.Before; +import annotations.Test; + +public class BeforePrivateAccess { + + private static int x = 0; + + @Before + private void before() { + x = 1; + } + + @Test + public void test() { + if (x != 1) { + throw new RuntimeException(); + } + x = 0; + } + + public static int x() { + return x; + } +} diff --git a/MyJUnit2/src/test/java/testCases/beforeAndAfterClass/AfterClassMethod.java b/MyJUnit2/src/test/java/testCases/beforeAndAfterClass/AfterClassMethod.java new file mode 100644 index 0000000..c4eb370 --- /dev/null +++ b/MyJUnit2/src/test/java/testCases/beforeAndAfterClass/AfterClassMethod.java @@ -0,0 +1,25 @@ +package testCases.beforeAndAfterClass; + +import annotations.AfterClass; +import annotations.Test; + +public class AfterClassMethod { + + private static int x = 0; + + @AfterClass + public void tearDown() { + x = 1; + } + + @Test + public void test() { + if (x != 0) { + throw new RuntimeException(); + } + } + + public static int x() { + return x; + } +} diff --git a/MyJUnit2/src/test/java/testCases/beforeAndAfterClass/BeforeAndAfterClassMethod.java b/MyJUnit2/src/test/java/testCases/beforeAndAfterClass/BeforeAndAfterClassMethod.java new file mode 100644 index 0000000..daa0a38 --- /dev/null +++ b/MyJUnit2/src/test/java/testCases/beforeAndAfterClass/BeforeAndAfterClassMethod.java @@ -0,0 +1,31 @@ +package testCases.beforeAndAfterClass; + +import annotations.AfterClass; +import annotations.BeforeClass; +import annotations.Test; + +public class BeforeAndAfterClassMethod { + + private static int x = 0; + + @BeforeClass + public void setUp() { + x = 2; + } + + @AfterClass + public void tearDown() { + x = 1; + } + + @Test + public void test() { + if (x != 2) { + throw new RuntimeException(); + } + } + + public static int x() { + return x; + } +} diff --git a/MyJUnit2/src/test/java/testCases/beforeAndAfterClass/BeforeAndAfterClassPrivateAccess.java b/MyJUnit2/src/test/java/testCases/beforeAndAfterClass/BeforeAndAfterClassPrivateAccess.java new file mode 100644 index 0000000..0df88fa --- /dev/null +++ b/MyJUnit2/src/test/java/testCases/beforeAndAfterClass/BeforeAndAfterClassPrivateAccess.java @@ -0,0 +1,29 @@ +package testCases.beforeAndAfterClass; + +import annotations.AfterClass; +import annotations.BeforeClass; +import annotations.Test; + +public class BeforeAndAfterClassPrivateAccess { + + private static int x = 0; + + @BeforeClass + private void before() { + x = 1; + } + + @Test + public void test() { + if (x != 1) { + throw new RuntimeException(); + } + } + + @AfterClass + private void after() { + x = 2; + } + + public int x() { return x; } +} diff --git a/MyJUnit2/src/test/java/testCases/beforeAndAfterClass/BeforeClassMethod.java b/MyJUnit2/src/test/java/testCases/beforeAndAfterClass/BeforeClassMethod.java new file mode 100644 index 0000000..30205bd --- /dev/null +++ b/MyJUnit2/src/test/java/testCases/beforeAndAfterClass/BeforeClassMethod.java @@ -0,0 +1,25 @@ +package testCases.beforeAndAfterClass; + +import annotations.Test; +import annotations.BeforeClass; + +public class BeforeClassMethod { + + private static int x = 0; + + @BeforeClass + public void setUp() { + x = 1; + } + + @Test + public void test() { + if (x != 1) { + throw new RuntimeException(); + } + } + + public static int x() { + return x; + } +} diff --git a/MyJUnit2/src/test/java/testCases/exceptions/CorrectException.java b/MyJUnit2/src/test/java/testCases/exceptions/CorrectException.java new file mode 100644 index 0000000..6d33efe --- /dev/null +++ b/MyJUnit2/src/test/java/testCases/exceptions/CorrectException.java @@ -0,0 +1,12 @@ +package testCases.exceptions; + +import annotations.Test; + +public class CorrectException { + + @Test(expected = ArithmeticException.class) + public void good() { + throw new ArithmeticException(); + } + +} diff --git a/MyJUnit2/src/test/java/testCases/exceptions/MoreFailing.java b/MyJUnit2/src/test/java/testCases/exceptions/MoreFailing.java new file mode 100644 index 0000000..47c55ed --- /dev/null +++ b/MyJUnit2/src/test/java/testCases/exceptions/MoreFailing.java @@ -0,0 +1,16 @@ +package testCases.exceptions; + +import annotations.Test; + +public class MoreFailing { + + @Test + public void failedNone() { + throw new NullPointerException(); + } + + @Test(expected = ArithmeticException.class) + public void failedWrong() { + throw new NullPointerException(); + } +} diff --git a/MyJUnit2/src/test/java/testCases/exceptions/NoExceptionGotten.java b/MyJUnit2/src/test/java/testCases/exceptions/NoExceptionGotten.java new file mode 100644 index 0000000..93e044e --- /dev/null +++ b/MyJUnit2/src/test/java/testCases/exceptions/NoExceptionGotten.java @@ -0,0 +1,10 @@ +package testCases.exceptions; + +import annotations.Test; + +public class NoExceptionGotten { + + @Test(expected = ArithmeticException.class) + public void empty() {} + +} diff --git a/MyJUnit2/src/test/java/testCases/exceptions/UnsupposedException.java b/MyJUnit2/src/test/java/testCases/exceptions/UnsupposedException.java new file mode 100644 index 0000000..0c2a997 --- /dev/null +++ b/MyJUnit2/src/test/java/testCases/exceptions/UnsupposedException.java @@ -0,0 +1,15 @@ +package testCases.exceptions; + +import annotations.Test; + +public class UnsupposedException { + + @Test + public void failed() { + throw new ArithmeticException(); + } + + @Test + public void good() {} + +} diff --git a/MyJUnit2/src/test/java/testCases/exceptions/WrongException.java b/MyJUnit2/src/test/java/testCases/exceptions/WrongException.java new file mode 100644 index 0000000..b00b820 --- /dev/null +++ b/MyJUnit2/src/test/java/testCases/exceptions/WrongException.java @@ -0,0 +1,12 @@ +package testCases.exceptions; + +import annotations.Test; + +public class WrongException { + + @Test(expected = ArithmeticException.class) + public void failed() { + throw new NullPointerException(); + } + +} diff --git a/MyJUnit2/src/test/java/testCases/other/Modifiers.java b/MyJUnit2/src/test/java/testCases/other/Modifiers.java new file mode 100644 index 0000000..edf887c --- /dev/null +++ b/MyJUnit2/src/test/java/testCases/other/Modifiers.java @@ -0,0 +1,19 @@ +package testCases.other; + +import annotations.Test; + +public class Modifiers { + + @Test + public void publicMethod() {} + + @Test + void defaultMethod() {} + + @Test + protected void protectedMethod() {} + + @Test + private void privateMethod() {} + +} diff --git a/MyJUnit2/src/test/java/testCases/other/PrivateConstructor.java b/MyJUnit2/src/test/java/testCases/other/PrivateConstructor.java new file mode 100644 index 0000000..7fdcee6 --- /dev/null +++ b/MyJUnit2/src/test/java/testCases/other/PrivateConstructor.java @@ -0,0 +1,12 @@ +package testCases.other; + +import annotations.Test; + +public class PrivateConstructor { + + private PrivateConstructor() {} + + @Test + public void test() {} + +} diff --git a/MyJUnit2/src/test/java/testCases/other/StaticModifier.java b/MyJUnit2/src/test/java/testCases/other/StaticModifier.java new file mode 100644 index 0000000..3662d16 --- /dev/null +++ b/MyJUnit2/src/test/java/testCases/other/StaticModifier.java @@ -0,0 +1,19 @@ +package testCases.other; + +import annotations.Test; + +public class StaticModifier { + + @Test + public static void publicMethod() {} + + @Test + static void defaultMethod() {} + + @Test + protected static void protectedMethod() {} + + @Test + private static void privateMethod() {} + +} diff --git a/MyJUnit2/src/test/java/testCases/skip/IgnoreEmpty.java b/MyJUnit2/src/test/java/testCases/skip/IgnoreEmpty.java new file mode 100644 index 0000000..46f67fa --- /dev/null +++ b/MyJUnit2/src/test/java/testCases/skip/IgnoreEmpty.java @@ -0,0 +1,12 @@ +package testCases.skip; + +import annotations.Test; + +public class IgnoreEmpty { + + @Test(ignore = "") + void skipTest() { + + } + +} diff --git a/MyJUnit2/src/test/java/testCases/skip/IgnoreFullMix.java b/MyJUnit2/src/test/java/testCases/skip/IgnoreFullMix.java new file mode 100644 index 0000000..282a03a --- /dev/null +++ b/MyJUnit2/src/test/java/testCases/skip/IgnoreFullMix.java @@ -0,0 +1,22 @@ +package testCases.skip; + +import annotations.Test; + +public class IgnoreFullMix { + + @Test(ignore = "reason") + void skipTest() { + + } + + @Test(expected = RuntimeException.class) + void failedTest() { + + } + + @Test + void passedTest() { + + } + +} diff --git a/MyJUnit2/src/test/java/testCases/skip/IgnoreOne.java b/MyJUnit2/src/test/java/testCases/skip/IgnoreOne.java new file mode 100644 index 0000000..17603c8 --- /dev/null +++ b/MyJUnit2/src/test/java/testCases/skip/IgnoreOne.java @@ -0,0 +1,12 @@ +package testCases.skip; + +import annotations.Test; + +public class IgnoreOne { + + @Test(ignore = "reason") + void skipTest() { + + } + +} diff --git a/MyJUnit2/src/test/java/testCases/skip/IgnoreTwo.java b/MyJUnit2/src/test/java/testCases/skip/IgnoreTwo.java new file mode 100644 index 0000000..d4e3579 --- /dev/null +++ b/MyJUnit2/src/test/java/testCases/skip/IgnoreTwo.java @@ -0,0 +1,17 @@ +package testCases.skip; + +import annotations.Test; + +public class IgnoreTwo { + + @Test(ignore = "reason1") + void skipTest1() { + + } + + @Test(ignore = "reason2") + void skipTest2() { + + } + +} diff --git a/MyJUnit2/src/test/java/testCases/skip/IgnoreWithFailed.java b/MyJUnit2/src/test/java/testCases/skip/IgnoreWithFailed.java new file mode 100644 index 0000000..875c741 --- /dev/null +++ b/MyJUnit2/src/test/java/testCases/skip/IgnoreWithFailed.java @@ -0,0 +1,17 @@ +package testCases.skip; + +import annotations.Test; + +public class IgnoreWithFailed { + + @Test(ignore = "reason") + void skipTest() { + + } + + @Test(expected = RuntimeException.class) + void failedTest() { + + } + +} diff --git a/MyJUnit2/src/test/java/testCases/skip/IgnoreWithRegular.java b/MyJUnit2/src/test/java/testCases/skip/IgnoreWithRegular.java new file mode 100644 index 0000000..c644efd --- /dev/null +++ b/MyJUnit2/src/test/java/testCases/skip/IgnoreWithRegular.java @@ -0,0 +1,17 @@ +package testCases.skip; + +import annotations.Test; + +public class IgnoreWithRegular { + + @Test(ignore = "reason") + void skipTest() { + + } + + @Test + void passedTest() { + + } + +}