In JUnit 5, you use the junitlauncher Ant task rather than the junit Ant task. Unfortunately, this isn’t a drop in replacement. For example, junitlauncher doesn’t offer the option to fork and run the JUnit tests. As a result, it also doesn’t have the nested sysproperty tag so you can pass system properties. This is a problem.
For the CodeRanch, we set a system property for the default file encoding. Since developers are around the world, we can’t assume everyone “just has” the encoding set.
Disclaimer
Since JUnit 5 functionality for Ant was introduced this year, I’m hoping what I did in this post is a short term workaround.
Option 1 – pass to Ant
You can pass the the properties to Ant itself as described on Stack Overflow. For example:
__JAVA_OPTIONS=-Dfile.encoding=ISO8859_1
pros:
- simple
cons:
- subpar – all the developers need to remember to do this. The reason we had it in Ant in the first place is so folks wouldn’t need to remember
- for some use cases, the desired system properties could be derived and not know when calling Ant
Option 2- Nashorn Code
Since JUnit 5 is being run in the same process as Ant itself, you need to set the system property in memory. Luckily, Ant allows you to run scripting in various languages. I chose Nashorn because it is built into Java. (There are other variants of this; see below)
<script language="javascript"> <![CDATA[ var imports = new JavaImporter(java.lang.System); imports.System.setProperty('file.encoding', 'ISO8859_1') ]]> </script>
Pros
- Short and simple
- Nashorn is deprecated for removal starting Java 11. This means at some point, it can be removed. (I’m hopeful that the Ant task itself will support system properties by then.
Cons
- Requires Java 8 or higher
- The System property is set for the remainder of the build (you could write another code block to null it out after the test if this is a problem)
Variants of option 2
If you are running Ant with a version of Java below Java 8, you could use this technique, but use Rhino instead. I didn’t test this, but I think the code is
importClass(java.lang.System); System.setProperty('file.encoding', 'ISO8859_1')
JUnit 5 itself uses Java 8 so nobody would be in the situation of pre-Java 8 and trying to use this blog post.If you are running Ant with a version of Java where Nashorn has been removed, you could use Groovy or Jython as the embedded language. The code is simpler. I didn’t chose this because it requires adding another jar to the Ant directory. I prefer to minimize these set up extensions. Especially for a feature like this which is likely to be temporary.
System.setProperty('file.encoding', 'ISO8859_1')