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.AbstractMojoRun 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>additionalClasspathElementsAdditional elements to be appended to the classpath.private java.lang.StringargLineArbitrary JVM options to set on the command line.private org.codehaus.plexus.configuration.PlexusConfigurationassertionsRaw assertions configuration.private org.codehaus.plexus.configuration.PlexusConfigurationbalancersRaw balancers configuration.private java.io.FileclassesDirectoryThe directory containing generated classes of the project being tested.private java.util.List<java.lang.String>classpathDependencyExcludesList of dependencies to exclude from the test classpath.private java.lang.StringclasspathDependencyScopeExcludeA dependency scope to exclude from the test classpath.private java.lang.BooleandebugStreamEnables a debug stream from each forked JVM.private static java.lang.StringDEFAULT_TARGETDefault target in the generated ANT file.private java.io.FiledirBase directory to invoke slave VMs in.private floatdynamicAssignmentRatioSpecifies the ratio of suites moved to dynamic assignment list.private static java.lang.String[]EMPTY_STRING_ARRAYAn empty String[].private static java.util.Map<java.lang.String,java.lang.String>EMPTY_STRING_STRING_MAPAn empty Map. private java.util.Map<java.lang.String,java.lang.String>environmentVariablesAdds an environment variable to any forked JVM.private java.util.List<java.lang.String>excludesA list of <exclude> elements specifying the tests (by pattern) that should be excluded in testing.private java.lang.StringfailurePropertyProperty to set to "true" if there is a failure in a test.private booleanhaltOnFailureStop the build process if there were failures or errors during test execution.private longheartbeatSets the heartbeat used to detect inactive/ hung forked tests (JVMs) to the given number of seconds.private java.lang.StringifNoTestsWhat to do when no tests were executed (all tests were ignored)? Possible values: ignore, fail, warn.private java.util.List<java.lang.String>includesA list of <include> elements specifying the tests (by pattern) that should be included in testing.private booleanisolateWorkingDirectoriesIf set totrueeach forked JVM gets a separate working directory under whatever is set indir.private java.lang.StringjunitArtifactNameSpecifies the name of the JUnit artifact used for running tests.private java.lang.StringjvmThe command used to invoke the Java Virtual Machine, default is 'java'.private java.lang.String[]jvmArgsAdd an additional argument to any forked JVM.private java.lang.StringjvmOutputActionWhat should be done on unexpected JVM output? JVM may write directly to the original descriptors, bypassing redirections of System.out and System.err.private booleanleaveTemporarySet to true to leave temporary files for diagnostics.private org.codehaus.plexus.configuration.PlexusConfigurationlistenersRaw listeners configuration.private java.lang.StringmaxMemorySet the maximum memory to be used by all forked JVMs.private org.apache.maven.artifact.metadata.ArtifactMetadataSourcemetadataSourceFor retrieval of artifact's metadata.private java.lang.BooleannewEnvironmentSet new environment for the forked process?private java.lang.StringonNonEmptyWorkDirectorySets the action performed when current work directory for a forked JVM is not empty andisolateWorkingDirectoriesis set to true.private java.lang.StringpackagingProject packaging mode to skip POM-projectsprivate java.lang.StringparallelismThe number of parallel f.private java.util.Map<java.lang.String,org.apache.maven.artifact.Artifact>pluginArtifactMapMap of plugin artifacts.private java.lang.StringprefixInitializes custom prefix for all junit4 properties.private booleanprintSummaryPrints the summary of all executed, ignored etc.private org.apache.maven.project.MavenProjectprojectThe Maven project objectprivate java.util.Map<java.lang.String,org.apache.maven.artifact.Artifact>projectArtifactMapMap of project artifacts.private org.apache.maven.repository.RepositorySystemrepositorySystemRepository.private org.apache.maven.artifact.resolver.ArtifactResolverresolverprivate java.lang.StringseedInitial random seed used for shuffling test suites and other sources of pseudo-randomness.private org.apache.maven.execution.MavenSessionsessionThe current build session instance.private booleanshuffleOnSlavePredictably shuffle tests order after balancing.private booleanskipTestsSet this to "true" to skip running tests, but still compile them.private java.lang.StringstatsPropertyPrefixSets the property prefix to which test statistics are saved.private java.io.FilesurefireReportsDirectoryThis parameter adds a listener emitting surefire-compatible XMLs if no other listeners are added.private booleansysoutsIf 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>systemPropertiesAdds a system property to any forked JVM.private java.io.FiletempDirThe directory to store temporary files in.private java.io.FiletestClassesDirectoryThe directory containing generated test classes of the project being tested.private booleanuniqueSuiteNamesAllows or disallow duplicate suite names in resource collections.private org.codehaus.plexus.configuration.PlexusConfigurationverbatimRaw section to copy/paste into ANT-driver.
-
Constructor Summary
Constructors Constructor Description JUnit4Mojo()
-
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description private voidaddArtifactClassPath(org.dom4j.Element cp, org.apache.maven.artifact.Artifact artifact)Append classpath elements of the given artefact to classpath.private voidappendRawXml(org.codehaus.plexus.configuration.PlexusConfiguration config, org.dom4j.Element elem)Append raw XML configuration.private voidcheckVersion(java.lang.String artifactName, java.lang.String versionSpec, org.apache.maven.artifact.Artifact artifact)EnsureartifactNamematches versionversionSpec.private org.dom4j.ElementcreateDocumentSkeleton(org.dom4j.Document doc)Creates a skeleton of a single-target ANT build file with JUnit4 task inside.private java.io.FilecreateTemporaryAntFile(org.dom4j.Document doc)Create a temporary ANT file for executing JUnit4 ANT task.voidexecute()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 voidpopulateJUnitElement(org.dom4j.Element junit4)Populate junit4 task with attributes and values.private org.apache.maven.artifact.resolver.ArtifactResolutionResultresolveArtifact(org.apache.maven.artifact.Artifact artifact, org.apache.maven.artifact.Artifact... filtered)Resolve a given artifact given exclusion list.private voidsetupTestClasspath(org.dom4j.Element junit4)Setup the classpath used for tests.private voidsetupTestInput(org.dom4j.Element junit4)Setup the input test suites (classes locations and patterns).private voidvalidateParameters()Initial validation of input parameters and configuration.
-
-
-
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 projectThe Maven project object
-
dir
@Parameter(property="project.build.directory", readonly=true, required=true) private java.io.File dirBase directory to invoke slave VMs in. Also noteisolateWorkingDirectoriesparameter.
-
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 fromRuntime.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 seedInitial 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
RandomizedRunnerso 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 totrueeach forked JVM gets a separate working directory under whatever is set indir. The directory naming for each JVM follows: "Jnum", where num is the forked JVM's number. Directories are created automatically and removed unlessleaveTemporaryis set totrue.
-
onNonEmptyWorkDirectory
@Parameter(defaultValue="fail") private java.lang.String onNonEmptyWorkDirectory
Sets the action performed when current work directory for a forked JVM is not empty andisolateWorkingDirectoriesis 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
leaveTemporaryparameter).
-
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 testClassesDirectoryThe 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 classesDirectoryThe directory containing generated classes of the project being tested. This will be included aftertestClassesDirectory.
-
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 surefireReportsDirectoryThis 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 junitArtifactNameSpecifies 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 jvmOutputActionWhat 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 istruebecause 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,TextReportreport 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 skipTestsSet 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 packagingProject 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-aThis 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> pluginArtifactMapMap of plugin artifacts.
-
projectArtifactMap
@Parameter(defaultValue="${project.artifactMap}", required=true, readonly=true) private java.util.Map<java.lang.String,org.apache.maven.artifact.Artifact> projectArtifactMapMap of project artifacts.
-
session
@Parameter(property="session", required=true, readonly=true) private org.apache.maven.execution.MavenSession sessionThe 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
-
-
Method Detail
-
execute
public void execute() throws org.apache.maven.plugin.MojoExecutionException, org.apache.maven.plugin.MojoFailureExceptionRun the mojo.- Throws:
org.apache.maven.plugin.MojoExecutionExceptionorg.apache.maven.plugin.MojoFailureException
-
validateParameters
private void validateParameters() throws org.apache.maven.plugin.MojoExecutionExceptionInitial 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.MojoExecutionExceptionEnsureartifactNamematches versionversionSpec.- 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.IOExceptionCreate 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).
-
-