Class JUnit4Mojo

java.lang.Object
org.apache.maven.plugin.AbstractMojo
com.carrotsearch.maven.plugins.junit4.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 List<String>
    Additional elements to be appended to the classpath.
    private String
    Arbitrary JVM options to set on the command line.
    private org.codehaus.plexus.configuration.PlexusConfiguration
    Raw assertions configuration.
    private org.codehaus.plexus.configuration.PlexusConfiguration
    Raw balancers configuration.
    private File
    The directory containing generated classes of the project being tested.
    private List<String>
    List of dependencies to exclude from the test classpath.
    private String
    A dependency scope to exclude from the test classpath.
    private Boolean
    Enables a debug stream from each forked JVM.
    private static final String
    Default target in the generated ANT file.
    private File
    Base directory to invoke slave VMs in.
    private float
    Specifies the ratio of suites moved to dynamic assignment list.
    private static final String[]
    An empty String[].
    private static final Map<String,String>
    An empty Mapinvalid input: '<'String, String>.
    private Map<String,String>
    Adds an environment variable to any forked JVM.
    private List<String>
    A list of <exclude> elements specifying the tests (by pattern) that should be excluded in testing.
    private String
    Property to set to "true" if there is a failure in a test.
    private boolean
    Stop the build process if there were failures or errors during test execution.
    private long
    Sets the heartbeat used to detect inactive/ hung forked tests (JVMs) to the given number of seconds.
    private String
    What to do when no tests were executed (all tests were ignored)? Possible values: ignore, fail, warn.
    private List<String>
    A list of <include> elements specifying the tests (by pattern) that should be included in testing.
    private boolean
    If set to true each forked JVM gets a separate working directory under whatever is set in dir.
    private String
    Specifies the name of the JUnit artifact used for running tests.
    private String
    The command used to invoke the Java Virtual Machine, default is 'java'.
    private String[]
    Add an additional argument to any forked JVM.
    private String
    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
    Set to true to leave temporary files for diagnostics.
    private org.codehaus.plexus.configuration.PlexusConfiguration
    Raw listeners configuration.
    private String
    Set the maximum memory to be used by all forked JVMs.
    private org.apache.maven.artifact.metadata.ArtifactMetadataSource
    For retrieval of artifact's metadata.
    private Boolean
    Set new environment for the forked process?
    private String
    Sets the action performed when current work directory for a forked JVM is not empty and isolateWorkingDirectories is set to true.
    private String
    Project packaging mode to skip POM-projects
    private String
    The number of parallel f.
    private Map<String,org.apache.maven.artifact.Artifact>
    Map of plugin artifacts.
    private String
    Initializes custom prefix for all junit4 properties.
    private boolean
    Prints the summary of all executed, ignored etc.
    private org.apache.maven.project.MavenProject
    The Maven project object
    private Map<String,org.apache.maven.artifact.Artifact>
    Map of project artifacts.
    private org.apache.maven.repository.RepositorySystem
    Repository.
    private org.apache.maven.artifact.resolver.ArtifactResolver
     
    private String
    Initial random seed used for shuffling test suites and other sources of pseudo-randomness.
    private org.apache.maven.execution.MavenSession
    The current build session instance.
    private boolean
    Predictably shuffle tests order after balancing.
    private boolean
    Set this to "true" to skip running tests, but still compile them.
    private String
    Sets the property prefix to which test statistics are saved.
    private File
    This parameter adds a listener emitting surefire-compatible XMLs if no other listeners are added.
    private boolean
    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 Map<String,String>
    Adds a system property to any forked JVM.
    private File
    The directory to store temporary files in.
    private File
    The directory containing generated test classes of the project being tested.
    private boolean
    Allows or disallow duplicate suite names in resource collections.
    private org.codehaus.plexus.configuration.PlexusConfiguration
    Raw section to copy/paste into ANT-driver.

    Fields inherited from interface org.apache.maven.plugin.Mojo

    ROLE
  • Constructor Summary

    Constructors
    Constructor
    Description
     
  • Method Summary

    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(String artifactName, 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 File
    createTemporaryAntFile(org.dom4j.Document doc)
    Create a temporary ANT file for executing JUnit4 ANT task.
    void
    Run the mojo.
    private Set<org.apache.maven.artifact.Artifact>
    filterArtifacts(org.dom4j.Element cp, 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
    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 Details

    • EMPTY_STRING_ARRAY

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

      private static final Map<String,String> EMPTY_STRING_STRING_MAP
      An empty Mapinvalid input: '<'String, String>.
    • DEFAULT_TARGET

      private static final String DEFAULT_TARGET
      Default target in the generated ANT file.
      See Also:
    • 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 File dir
      Base directory to invoke slave VMs in. Also note isolateWorkingDirectories parameter.
    • tempDir

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

      @Parameter(defaultValue="1") private 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 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 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 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 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 String[] jvmArgs
      Add an additional argument to any forked JVM.
    • argLine

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

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

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

      @Parameter(defaultValue="java") private 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 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 File classesDirectory
      The directory containing generated classes of the project being tested. This will be included after testClassesDirectory.
    • includes

      @Parameter private List<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 List<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 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 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 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 String packaging
      Project packaging mode to skip POM-projects
    • classpathDependencyExcludes

      @Parameter private List<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 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 List<String> additionalClasspathElements
      Additional elements to be appended to the classpath.
    • prefix

      @Parameter private 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 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 Boolean newEnvironment
      Set new environment for the forked process?
    • ifNoTests

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

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

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

      @Parameter(defaultValue="${project.artifactMap}", required=true, readonly=true) private Map<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 Details

    • JUnit4Mojo

      public JUnit4Mojo()
  • Method Details

    • 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(String artifactName, 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 File createTemporaryAntFile(org.dom4j.Document doc) throws IOException
      Create a temporary ANT file for executing JUnit4 ANT task.
      Throws:
      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 Set<org.apache.maven.artifact.Artifact> filterArtifacts(org.dom4j.Element cp, 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).