JUnitParams icon indicating copy to clipboard operation
JUnitParams copied to clipboard

Unable to pass newlines as a parameter (dupe of #30)

Open coopstah13 opened this issue 7 years ago • 4 comments

According to issue #30 the workaround for passing in newlines is to use a class provider. I'm using class providers nearly exclusively and my trailing newline is still trimmed.

    @SuppressWarnings("unused")
    public static Object[] provideInvalidValues() {
        List<String> invalidValues = new ArrayList<>();

        invalidValues.addAll(BlankStringProvider.BLANK_STRINGS);

        invalidValues.add("1a"); // starts with a number
        invalidValues.add("a-"); // contains a hyphen
        invalidValues.add("a\n"); // contains a new line
        invalidValues.add("a\r"); // contains a carriage return
        invalidValues.add("a\nb"); // contains a new line
        invalidValues.add("a\rb"); // contains a carriage return
        invalidValues.add("a 1"); // contains a space
        invalidValues.add("a∫ı"); // contains funky characters
        invalidValues.add("aü"); // also contains funky characters

        return invalidValues.toArray();
    }

In this example a\n and a\r are provided in the test as just a. I don't really care about how the "test readability" looks, I just want to test the data I want to test.

coopstah13 avatar Dec 06 '17 15:12 coopstah13

I did some debugging, I've traced the issue down to the InvokedParameterisedMethod class, in the constructor if the value of params is a string, then it is passed through the Utils.splitAtCommaOrPipe method, which is trimming the string

coopstah13 avatar Dec 06 '17 16:12 coopstah13

To workaround this I am using a simple String wrapper:

public final class Text {

  private final String text;

  private Text(final String text) {
    this.text = text;
  }

  public static Text of(final String text) {
    return new Text(text);
  }

  @Override
  public String toString() {
    return text;
  }

}

Then you can use it in your provider method:

public static Object[] provideInvalidValues() {
  List<String> invalidValues = new ArrayList<>();

  invalidValues.add(Text.of(" "));

  return invalidValues.toArray();
}

stef2georg avatar Jun 15 '18 10:06 stef2georg

@coopstah13 you should use 2-dimensional array as result of provideInvalidValues. Something like:

  @SuppressWarnings("unused")
  public static Object[][] provideInvalidValues() {
    return new Object[]{new String[]{"a\n", "a\r"}};
  }

should be enough for your case.

aleskiewicz avatar Jan 17 '19 12:01 aleskiewicz

I'm using the wrapper class workaround. I get the 2d array works, my largest issue is that it's easy to do it wrong and you won't even know.

coopstah13 avatar Jan 17 '19 21:01 coopstah13