0

In a Maven application I need to test a method with a different encoding and just one of them. The others must use the encoding provided by System.getProperty("file.encoding").

For example:

@Test
public void test1() {...} // regular encoding

@Test
public void test2() {...} // regular encoding

@Test
public void test3() {...} // regular encoding

[...]

@Test
public void testEncoding() {...} // custom encoding!!!

I cannot change the encoding with System.setProperty("file.encoding", "...") because is cached and I want a procedure that can be versionable (i.e. independent by an IDE like IDEA or Eclipse and working for anyone has downloaded the code).

Is there any way via JUnit or Maven plugin to do so?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Mirianna
  • 910
  • 1
  • 8
  • 18
  • 3
    The proper way would probably be to abstract away the access to file.encoding (which really, you should try not to rely on: always be explicit with your character sets), and then test by mocking this abstraction so your program can control the encoding at runtime. I'm posting this as a comment as it is a bit hand-wave-y. – Mark Rotteveel Apr 14 '21 at 11:37
  • 2
    See https://stackoverflow.com/questions/361975/setting-the-default-java-character-encoding for potential hacks. But, follow @MarkRotteveel's advice and change the code so a specific encoding (or an encoding-aware implementation) can be passed to your code in each test. – Joe Apr 14 '21 at 11:46
  • Thank you for the advices @MarkRotteveel and @Joe, my concern is that as the application grows it may be harder to track every single point where `System.getProperty("file.encoding")` affects the results. And I'm also concerned that I am not aware of all the Java APIs using `System.getProperty("file.encoding")`. – Mirianna Apr 14 '21 at 12:11
  • The solution therefor is to write your application in a way that does not rely on the default character set / file.encoding. – Mark Rotteveel Apr 14 '21 at 14:58

1 Answers1

0

Method 1: Optional Charset parameter

You do not need to test your method using the file.encoding property. As you probably know, this property will only set the DEFAULT encoding for methods which have an optional encoding/charset parameter.

However, all those methods (without the charset parameter) are considered a bad habit. That said, overload your methods with an optional parameter Charset and the method without this optional parameter should pass in Charset.defaultCharset().

This way you can easily test your methods accordingly.

Method 2: Maven-Invoker-Plugin

Use the maven-invoker-plugin to create isolated tests in src/it/<testname>. Those are fully isolated maven projects. Examples can be found in almost any maven project. You can pass system arguments via surefire for example.

If this

Benjamin Marwell
  • 1,173
  • 1
  • 13
  • 36