简体   繁体   中英

How to test a method with specific file.encoding option?

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 (ie 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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM