1

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!
  • 1
    "but I keep receiving errors of different kinds" - it would be mighty helpful if you included one or more examples of errors you've received :) That being said, `mvn test "-Dtest=$name"` might solve the problem – Mathias R. Jessen Aug 12 '21 at 13:53
  • @MathiasR.Jessen thank you so much! – kyotosakobe Aug 12 '21 at 14:25
  • Why do you need to get all files separately instead of using Maven (maven-surefire-plugin) itself? Why do you need that? Let Maven do the work it's easier... – khmarbaise Aug 12 '21 at 20:26

1 Answers1

1

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.

mklement0
  • 382,024
  • 64
  • 607
  • 775
  • omg thank you so much, you're a lifesaver – kyotosakobe Aug 12 '21 at 14:12
  • My pleasure, @kyotosakobe. I just noticed that Mathias had essentially provided the solution in a comment too, but I hope the explanation is also useful. – mklement0 Aug 12 '21 at 14:13
  • 1
    oh wow i didn't even notice, i haven't posted much on stack overflow so i completely forgot to check the comments properly. thank you lol – kyotosakobe Aug 12 '21 at 14:26