简体   繁体   中英

How to convert string to have \n instead of line break

AssertThat( myString1 , is (myString2));

is getting failed.

So I checked two values through an eclipse debug "variables" console.

myString1

hello
my name is 
alex

myString2

hello\n my name is\n alex

If I try with String.compareTo, it failed.

My question is two, 1. Are those actually same? (console displays)? 2. If not, how do I convert from myString1 to myString2?

Use this import-- org.apache.commons.lang.StringEscapeUtils

StringEscapeUtils.escapeJava(StringVariableNameHere);

Would serve as a hint to your question

1) No, they are obviously not the same.

2) What about this:

myString2 = myString1.replaceAll("\\n", "\\\\n");

or better:

myString2 = myString1.replaceAll(System.getProperty("line.separator", "\\\\n");

There is no need to use external packages.

The key thing to understand here is: we can not tell you about your requirements .

It is really simple: two string objects are only equal, if a.equals(b) returns true. So, obviously, the two strings from your example are not equal.

But the questions behind that are: does it matter to your production code; and thus: how should your test code deal with it?!

Meaning: you as the owner of production and test code, you have to understand if you care about those newline characters. There could be plenty of options to address your failing test:

  1. Why does the one string have \\n chars in it; and the other has not? Is your expected value simply wrong?
  2. Or is your expected value really "correct"; and thus: the production code is giving an unexpected result; thus indicating that there is a problem within your production code?

So, yes, the correct answer might be to massage that assert (or its expected value) to allow for such \\n chars. But the correct answer could as well be "fix broken production code". As you are using assertThat, you might write your own matcher for strings that simply ignores \\n chars somehow; and that would give "true" for your example strings ...

As said: there are several options to "fix" this; but you have to understand which one really fixes your problem.

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