Issue
I need to use PowerShell to run mvn test
on all test cases individually. I tried to create a Foreach
loop where I recursively pass every test case through mvn test -Dtest
but I keep receiving errors of different kinds, but in every case, the individual tests don't run for some reason.
Get-ChildItem -Path "C:\Users\me\project\src\test" -Filter *.java -Recurse -Name -ErrorAction SilentlyContinue -Force | ForEach-Object {
$file = ($_ -split '\\')[-1]
$name = $file.substring(0,$file.length-5)
mvn test -Dtest=$name
}
However, when I don't pass a variable to mvn test -Dtest
and give it an actual test class name (for example: mvn test -Dtest=AddTest
), the test runs normally. The problems seems to be with $name
getting passed to -Dtest
because I opened this script in VS Code and it said that the $name
variable is never used after being declared even though I use it in the very next line with mvn test -Dtest=$name
.
Here is the main error I've been receiving
Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.22.0:test (default-test) on project: No tests were executed!
Solution
You're seeing an unfortunate bug in PowerShell's parameter binder, still present as of PowerShell 7.2.
To work around it, pass your argument as an expandable string, as Mathias R. Jessen suggests in a comment:
mvn test "-Dtest=$name"
In short, the bug is:
If an argument is
-
-prefixed, embedded variable references such as$name
are unexpectedly not expanded, unless there happens to be a preceding:
character.Presumably, PowerShell thinks that everything following the
-
, even past a=
, is a parameter name, and is therefore used verbatim (in PowerShell, it is:
that separates a parameter name from its value if passed as a single token, which is not common).See GitHub issue #14587.
Answered By - mklement0