Class JUnit4Mojo

  • All Implemented Interfaces:
    org.apache.maven.plugin.ContextEnabled, org.apache.maven.plugin.Mojo

    @Mojo(name="junit4",
          defaultPhase=TEST,
          threadSafe=true,
          requiresProject=true,
          requiresDependencyResolution=TEST)
    public class JUnit4Mojo
    extends org.apache.maven.plugin.AbstractMojo
    Run tests using a delegation to Randomized Testing's JUnit4 ANT task.
    • Field Summary

      Fields 
      Modifier and Type Field Description
      private java.util.List<java.lang.String> additionalClasspathElements
      Additional elements to be appended to the classpath.
      private java.lang.String argLine
      Arbitrary JVM options to set on the command line.
      private org.codehaus.plexus.configuration.PlexusConfiguration assertions
      Raw assertions configuration.
      private org.codehaus.plexus.configuration.PlexusConfiguration balancers
      Raw balancers configuration.
      private java.io.File classesDirectory
      The directory containing generated classes of the project being tested.
      private java.util.List<java.lang.String> classpathDependencyExcludes
      List of dependencies to exclude from the test classpath.
      private java.lang.String classpathDependencyScopeExclude
      A dependency scope to exclude from the test classpath.
      private java.lang.Boolean debugStream
      Enables a debug stream from each forked JVM.
      private static java.lang.String DEFAULT_TARGET
      Default target in the generated ANT file.
      private java.io.File dir
      Base directory to invoke slave VMs in.
      private float dynamicAssignmentRatio
      Specifies the ratio of suites moved to dynamic assignment list.
      private static java.lang.String[] EMPTY_STRING_ARRAY
      An empty String[].
      private static java.util.Map<java.lang.String,​java.lang.String> EMPTY_STRING_STRING_MAP
      An empty Map.
      private java.util.Map<java.lang.String,​java.lang.String> environmentVariables
      Adds an environment variable to any forked JVM.
      private java.util.List<java.lang.String> excludes
      A list of <exclude> elements specifying the tests (by pattern) that should be excluded in testing.
      private java.lang.String failureProperty
      Property to set to "true" if there is a failure in a test.
      private boolean haltOnFailure
      Stop the build process if there were failures or errors during test execution.
      private long heartbeat
      Sets the heartbeat used to detect inactive/ hung forked tests (JVMs) to the given number of seconds.
      private java.lang.String ifNoTests
      What to do when no tests were executed (all tests were ignored)? Possible values: ignore, fail, warn.
      private java.util.List<java.lang.String> includes
      A list of <include> elements specifying the tests (by pattern) that should be included in testing.
      private boolean isolateWorkingDirectories
      If set to true each forked JVM gets a separate working directory under whatever is set in dir.
      private java.lang.String junitArtifactName
      Specifies the name of the JUnit artifact used for running tests.
      private java.lang.String jvm
      The command used to invoke the Java Virtual Machine, default is 'java'.
      private java.lang.String[] jvmArgs
      Add an additional argument to any forked JVM.
      private java.lang.String jvmOutputAction
      What should be done on unexpected JVM output? JVM may write directly to the original descriptors, bypassing redirections of System.out and System.err.
      private boolean leaveTemporary
      Set to true to leave temporary files for diagnostics.
      private org.codehaus.plexus.configuration.PlexusConfiguration listeners
      Raw listeners configuration.
      private java.lang.String maxMemory
      Set the maximum memory to be used by all forked JVMs.
      private org.apache.maven.artifact.metadata.ArtifactMetadataSource metadataSource
      For retrieval of artifact's metadata.
      private java.lang.Boolean newEnvironment
      Set new environment for the forked process?
      private java.lang.String onNonEmptyWorkDirectory
      Sets the action performed when current work directory for a forked JVM is not empty and isolateWorkingDirectories is set to true.
      private java.lang.String packaging
      Project packaging mode to skip POM-projects
      private java.lang.String parallelism
      The number of parallel f.
      private java.util.Map<java.lang.String,​org.apache.maven.artifact.Artifact> pluginArtifactMap
      Map of plugin artifacts.
      private java.lang.String prefix
      Initializes custom prefix for all junit4 properties.
      private boolean printSummary
      Prints the summary of all executed, ignored etc.
      private org.apache.maven.project.MavenProject project
      The Maven project object
      private java.util.Map<java.lang.String,​org.apache.maven.artifact.Artifact> projectArtifactMap
      Map of project artifacts.
      private org.apache.maven.repository.RepositorySystem repositorySystem
      Repository.
      private org.apache.maven.artifact.resolver.ArtifactResolver resolver  
      private java.lang.String seed
      Initial random seed used for shuffling test suites and other sources of pseudo-randomness.
      private org.apache.maven.execution.MavenSession session
      The current build session instance.
      private boolean shuffleOnSlave
      Predictably shuffle tests order after balancing.
      private boolean skipTests
      Set this to "true" to skip running tests, but still compile them.
      private java.lang.String statsPropertyPrefix
      Sets the property prefix to which test statistics are saved.
      private java.io.File surefireReportsDirectory
      This parameter adds a listener emitting surefire-compatible XMLs if no other listeners are added.
      private boolean sysouts
      If set to true, any sysout and syserr calls will be written to original output and error streams (and in effect will appear as "jvm output".
      private java.util.Map<java.lang.String,​java.lang.String> systemProperties
      Adds a system property to any forked JVM.
      private java.io.File tempDir
      The directory to store temporary files in.
      private java.io.File testClassesDirectory
      The directory containing generated test classes of the project being tested.
      private boolean uniqueSuiteNames
      Allows or disallow duplicate suite names in resource collections.
      private org.codehaus.plexus.configuration.PlexusConfiguration verbatim
      Raw section to copy/paste into ANT-driver.
      • Fields inherited from interface org.apache.maven.plugin.Mojo

        ROLE
    • Constructor Summary

      Constructors 
      Constructor Description
      JUnit4Mojo()  
    • Method Summary

      All Methods Instance Methods Concrete Methods 
      Modifier and Type Method Description
      private void addArtifactClassPath​(org.dom4j.Element cp, org.apache.maven.artifact.Artifact artifact)
      Append classpath elements of the given artefact to classpath.
      private void appendRawXml​(org.codehaus.plexus.configuration.PlexusConfiguration config, org.dom4j.Element elem)
      Append raw XML configuration.
      private void checkVersion​(java.lang.String artifactName, java.lang.String versionSpec, org.apache.maven.artifact.Artifact artifact)
      Ensure artifactName matches version versionSpec.
      private org.dom4j.Element createDocumentSkeleton​(org.dom4j.Document doc)
      Creates a skeleton of a single-target ANT build file with JUnit4 task inside.
      private java.io.File createTemporaryAntFile​(org.dom4j.Document doc)
      Create a temporary ANT file for executing JUnit4 ANT task.
      void execute()
      Run the mojo.
      private java.util.Set<org.apache.maven.artifact.Artifact> filterArtifacts​(org.dom4j.Element cp, java.util.Set<org.apache.maven.artifact.Artifact> artifacts, org.apache.maven.artifact.resolver.filter.ArtifactFilter filter)
      Return a new set containing only the artifacts accepted by the given filter.
      private void populateJUnitElement​(org.dom4j.Element junit4)
      Populate junit4 task with attributes and values.
      private org.apache.maven.artifact.resolver.ArtifactResolutionResult resolveArtifact​(org.apache.maven.artifact.Artifact artifact, org.apache.maven.artifact.Artifact... filtered)
      Resolve a given artifact given exclusion list.
      private void setupTestClasspath​(org.dom4j.Element junit4)
      Setup the classpath used for tests.
      private void setupTestInput​(org.dom4j.Element junit4)
      Setup the input test suites (classes locations and patterns).
      private void validateParameters()
      Initial validation of input parameters and configuration.
      • Methods inherited from class org.apache.maven.plugin.AbstractMojo

        getLog, getPluginContext, setLog, setPluginContext
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    • Field Detail

      • EMPTY_STRING_ARRAY

        private static final java.lang.String[] EMPTY_STRING_ARRAY
        An empty String[].
      • EMPTY_STRING_STRING_MAP

        private static final java.util.Map<java.lang.String,​java.lang.String> EMPTY_STRING_STRING_MAP
        An empty Map.
      • DEFAULT_TARGET

        private static final java.lang.String DEFAULT_TARGET
        Default target in the generated ANT file.
        See Also:
        Constant Field Values
      • project

        @Parameter(property="project",
                   readonly=true,
                   required=true)
        private org.apache.maven.project.MavenProject project
        The Maven project object
      • dir

        @Parameter(property="project.build.directory",
                   readonly=true,
                   required=true)
        private java.io.File dir
        Base directory to invoke slave VMs in. Also note isolateWorkingDirectories parameter.
      • tempDir

        @Parameter(property="project.build.directory")
        private java.io.File tempDir
        The directory to store temporary files in.
      • parallelism

        @Parameter(defaultValue="1")
        private java.lang.String parallelism
        The number of parallel f. Can be set to a constant "max" for the number of cores returned from Runtime.availableProcessors() or "auto" for sensible defaults depending on the number of cores. The default is a single subprocess.

        Note that this setting forks physical JVM processes so it multiplies the requirements for heap memory, IO, etc.

      • failureProperty

        @Parameter
        private java.lang.String failureProperty
        Property to set to "true" if there is a failure in a test. The use of this property is discouraged in Maven (builds should be declarative).
      • seed

        @Parameter(property="tests.seed",
                   defaultValue="")
        private java.lang.String seed
        Initial random seed used for shuffling test suites and other sources of pseudo-randomness. If not set, any random value is set.

        The seed's format is compatible with RandomizedRunner so that seed can be fixed for suites and methods alike. Unless the global prefix of randomized testing properties is changed, the seed can be overridden using "tests.seed" property.

      • shuffleOnSlave

        @Parameter(defaultValue="true")
        private boolean shuffleOnSlave
        Predictably shuffle tests order after balancing. This will help in spreading lighter and heavier tests over a single slave's execution timeline while still keeping the same tests order depending on the seed.
      • printSummary

        @Parameter(defaultValue="true")
        private boolean printSummary
        Prints the summary of all executed, ignored etc. tests at the end.
      • haltOnFailure

        @Parameter(defaultValue="true")
        private boolean haltOnFailure
        Stop the build process if there were failures or errors during test execution.
      • isolateWorkingDirectories

        @Parameter(defaultValue="true")
        private boolean isolateWorkingDirectories
        If set to true each forked JVM gets a separate working directory under whatever is set in dir. The directory naming for each JVM follows: "Jnum", where num is the forked JVM's number. Directories are created automatically and removed unless leaveTemporary is set to true.
      • onNonEmptyWorkDirectory

        @Parameter(defaultValue="fail")
        private java.lang.String onNonEmptyWorkDirectory
        Sets the action performed when current work directory for a forked JVM is not empty and isolateWorkingDirectories is set to true.
      • sysouts

        @Parameter(defaultValue="false")
        private boolean sysouts
        If set to true, any sysout and syserr calls will be written to original output and error streams (and in effect will appear as "jvm output". By default sysout and syserrs are captured and proxied to the event stream to be synchronized with other test events but occasionally one may want to synchronize them with direct JVM output (to synchronize with compiler output or GC output for example).
      • dynamicAssignmentRatio

        @Parameter(defaultValue="0.25")
        private float dynamicAssignmentRatio
        Specifies the ratio of suites moved to dynamic assignment list. A dynamic assignment list dispatches suites to the first idle slave JVM. Theoretically this is an optimal strategy, but it is usually better to have some static assignments to avoid communication costs.

        A ratio of 0 means only static assignments are used. A ratio of 1 means only dynamic assignments are used.

        The list of dynamic assignments is sorted by decreasing cost (always) and is inherently prone to race conditions in distributing suites. Should there be an error based on suite-dependency it will not be directly repeatable. In such case use the per-slave-jvm list of suites file dumped to disk for each slave JVM. (see leaveTemporary parameter).

      • maxMemory

        @Parameter
        private java.lang.String maxMemory
        Set the maximum memory to be used by all forked JVMs. The value as defined by -mx or -Xmx in the java command line options.
      • leaveTemporary

        @Parameter
        private boolean leaveTemporary
        Set to true to leave temporary files for diagnostics.
      • jvmArgs

        @Parameter
        private java.lang.String[] jvmArgs
        Add an additional argument to any forked JVM.
      • argLine

        @Parameter(property="argLine")
        private java.lang.String argLine
        Arbitrary JVM options to set on the command line.
      • systemProperties

        @Parameter
        private java.util.Map<java.lang.String,​java.lang.String> systemProperties
        Adds a system property to any forked JVM.
      • environmentVariables

        @Parameter
        private java.util.Map<java.lang.String,​java.lang.String> environmentVariables
        Adds an environment variable to any forked JVM.
      • jvm

        @Parameter(defaultValue="java")
        private java.lang.String jvm
        The command used to invoke the Java Virtual Machine, default is 'java'. The command is resolved by java.lang.Runtime.exec().
      • testClassesDirectory

        @Parameter(defaultValue="${project.build.testOutputDirectory}")
        private java.io.File testClassesDirectory
        The directory containing generated test classes of the project being tested. This will be included at the beginning of the test classpath.
      • classesDirectory

        @Parameter(defaultValue="${project.build.outputDirectory}")
        private java.io.File classesDirectory
        The directory containing generated classes of the project being tested. This will be included after testClassesDirectory.
      • includes

        @Parameter
        private java.util.List<java.lang.String> includes
        A list of <include> elements specifying the tests (by pattern) that should be included in testing. When not specified defaults to:
         <include>**/*Test.class</include>
         <include>**/Test*.class</include>
         
        Note that this may result in nested classes being included for tests. Use proper exclusion patterns.
      • excludes

        @Parameter
        private java.util.List<java.lang.String> excludes
        A list of <exclude> elements specifying the tests (by pattern) that should be excluded in testing. When not specified defaults to:
         <exclude>**/*$*.class</exclude>
         
        This patterns excludes any nested classes that might otherwise be included.
      • surefireReportsDirectory

        @Parameter(defaultValue="${project.build.directory}/surefire-reports")
        private java.io.File surefireReportsDirectory
        This parameter adds a listener emitting surefire-compatible XMLs if no other listeners are added. If there are any configured listeners, this parameter is omitted (you can add a maven-compatible listener manually).
      • junitArtifactName

        @Parameter(property="junitArtifactName",
                   defaultValue="junit:junit")
        private java.lang.String junitArtifactName
        Specifies the name of the JUnit artifact used for running tests. JUnit dependency must be in at least version 4.10.
      • jvmOutputAction

        @Parameter(property="jvmOutputAction",
                   defaultValue="pipe,warn")
        private java.lang.String jvmOutputAction
        What should be done on unexpected JVM output? JVM may write directly to the original descriptors, bypassing redirections of System.out and System.err. Typically, these messages will be important and should fail the build (permgen space exceeded, compiler errors, crash dumps). However, certain legitimate logs (gc activity, class loading logs) are also printed to these streams so sometimes the output can be ignored.

        Allowed values (any comma-delimited combination of): ignore, pipe, warn, fail.

      • uniqueSuiteNames

        @Parameter(defaultValue="true")
        private boolean uniqueSuiteNames
        Allows or disallow duplicate suite names in resource collections. By default this option is true because certain ANT-compatible report types (like XML reports) will have a problem with duplicate suite names (will overwrite files).
      • listeners

        @Parameter
        private org.codehaus.plexus.configuration.PlexusConfiguration listeners
        Raw listeners configuration. Same XML as for ANT.
      • assertions

        @Parameter
        private org.codehaus.plexus.configuration.PlexusConfiguration assertions
        Raw assertions configuration. Same XML as for ANT.
      • balancers

        @Parameter
        private org.codehaus.plexus.configuration.PlexusConfiguration balancers
        Raw balancers configuration. Same XML as for ANT.
      • verbatim

        @Parameter
        private org.codehaus.plexus.configuration.PlexusConfiguration verbatim
        Raw section to copy/paste into ANT-driver.
      • heartbeat

        @Parameter(defaultValue="0")
        private long heartbeat
        Sets the heartbeat used to detect inactive/ hung forked tests (JVMs) to the given number of seconds. The heartbeat detects no-event intervals and will report them to listeners. Notably, TextReport report will emit heartbeat information (to a file or console).

        Setting the heartbeat to zero means no detection.

      • skipTests

        @Parameter(property="skipTests",
                   defaultValue="false")
        private boolean skipTests
        Set this to "true" to skip running tests, but still compile them. Its use is NOT RECOMMENDED, but quite convenient on occasion.
      • packaging

        @Parameter(defaultValue="${project.packaging}",
                   readonly=true)
        private java.lang.String packaging
        Project packaging mode to skip POM-projects
      • classpathDependencyExcludes

        @Parameter
        private java.util.List<java.lang.String> classpathDependencyExcludes
        List of dependencies to exclude from the test classpath. Each dependency string must follow the format groupId:artifactId. For example: org.acme:project-a

        This is modeled after surefire. An excluded dependency does not mean its transitive dependencies will also be excluded.

      • classpathDependencyScopeExclude

        @Parameter(defaultValue="")
        private java.lang.String classpathDependencyScopeExclude
        A dependency scope to exclude from the test classpath. The scope can be one of the following scopes:

        • compile - system, provided, compile
        • runtime - compile, runtime
        • test - system, provided, compile, runtime, test
      • additionalClasspathElements

        @Parameter
        private java.util.List<java.lang.String> additionalClasspathElements
        Additional elements to be appended to the classpath.
      • prefix

        @Parameter
        private java.lang.String prefix
        Initializes custom prefix for all junit4 properties. This must be consistent across all junit4 invocations if done from the same classpath. Use only when REALLY needed.
      • debugStream

        @Parameter
        private java.lang.Boolean debugStream
        Enables a debug stream from each forked JVM. This will create an additional file next to each events file. For debugging the framework only, not a general-purpose setting.
      • newEnvironment

        @Parameter
        private java.lang.Boolean newEnvironment
        Set new environment for the forked process?
      • ifNoTests

        @Parameter(defaultValue="ignore")
        private java.lang.String ifNoTests
        What to do when no tests were executed (all tests were ignored)? Possible values: ignore, fail, warn.
      • statsPropertyPrefix

        @Parameter
        private java.lang.String statsPropertyPrefix
        Sets the property prefix to which test statistics are saved.
      • pluginArtifactMap

        @Parameter(defaultValue="${plugin.artifactMap}",
                   required=true,
                   readonly=true)
        private java.util.Map<java.lang.String,​org.apache.maven.artifact.Artifact> pluginArtifactMap
        Map of plugin artifacts.
      • projectArtifactMap

        @Parameter(defaultValue="${project.artifactMap}",
                   required=true,
                   readonly=true)
        private java.util.Map<java.lang.String,​org.apache.maven.artifact.Artifact> projectArtifactMap
        Map of project artifacts.
      • session

        @Parameter(property="session",
                   required=true,
                   readonly=true)
        private org.apache.maven.execution.MavenSession session
        The current build session instance.
      • repositorySystem

        @Component
        private org.apache.maven.repository.RepositorySystem repositorySystem
        Repository.
      • metadataSource

        @Component
        private org.apache.maven.artifact.metadata.ArtifactMetadataSource metadataSource
        For retrieval of artifact's metadata.
      • resolver

        @Component
        private org.apache.maven.artifact.resolver.ArtifactResolver resolver
    • Constructor Detail

      • JUnit4Mojo

        public JUnit4Mojo()
    • Method Detail

      • execute

        public void execute()
                     throws org.apache.maven.plugin.MojoExecutionException,
                            org.apache.maven.plugin.MojoFailureException
        Run the mojo.
        Throws:
        org.apache.maven.plugin.MojoExecutionException
        org.apache.maven.plugin.MojoFailureException
      • validateParameters

        private void validateParameters()
                                 throws org.apache.maven.plugin.MojoExecutionException
        Initial validation of input parameters and configuration.
        Throws:
        org.apache.maven.plugin.MojoExecutionException
      • checkVersion

        private void checkVersion​(java.lang.String artifactName,
                                  java.lang.String versionSpec,
                                  org.apache.maven.artifact.Artifact artifact)
                           throws org.apache.maven.plugin.MojoExecutionException
        Ensure artifactName matches version versionSpec.
        Throws:
        org.apache.maven.plugin.MojoExecutionException
      • populateJUnitElement

        private void populateJUnitElement​(org.dom4j.Element junit4)
        Populate junit4 task with attributes and values.
      • appendRawXml

        private void appendRawXml​(org.codehaus.plexus.configuration.PlexusConfiguration config,
                                  org.dom4j.Element elem)
        Append raw XML configuration.
      • createTemporaryAntFile

        private java.io.File createTemporaryAntFile​(org.dom4j.Document doc)
                                             throws java.io.IOException
        Create a temporary ANT file for executing JUnit4 ANT task.
        Throws:
        java.io.IOException
      • createDocumentSkeleton

        private org.dom4j.Element createDocumentSkeleton​(org.dom4j.Document doc)
        Creates a skeleton of a single-target ANT build file with JUnit4 task inside.
      • addArtifactClassPath

        private void addArtifactClassPath​(org.dom4j.Element cp,
                                          org.apache.maven.artifact.Artifact artifact)
        Append classpath elements of the given artefact to classpath.
      • resolveArtifact

        private org.apache.maven.artifact.resolver.ArtifactResolutionResult resolveArtifact​(org.apache.maven.artifact.Artifact artifact,
                                                                                            org.apache.maven.artifact.Artifact... filtered)
        Resolve a given artifact given exclusion list. (copied from surefire).
      • setupTestClasspath

        private void setupTestClasspath​(org.dom4j.Element junit4)
        Setup the classpath used for tests.
      • filterArtifacts

        private java.util.Set<org.apache.maven.artifact.Artifact> filterArtifacts​(org.dom4j.Element cp,
                                                                                  java.util.Set<org.apache.maven.artifact.Artifact> artifacts,
                                                                                  org.apache.maven.artifact.resolver.filter.ArtifactFilter filter)
        Return a new set containing only the artifacts accepted by the given filter.
      • setupTestInput

        private void setupTestInput​(org.dom4j.Element junit4)
        Setup the input test suites (classes locations and patterns).