简体   繁体   中英

Why are there brackets after my String's value?

I have a test like this:

String dir = "/foo";
String fileName = "hello.txt";
String pathString = dir + "/" + fileName;
String text = "hello world!";
MyTask task = new MyTask();

FileSystem fs = Jimfs.newFileSystem(Configuration.unix());

Path foo = fs.getPath(dir);
Files.createDirectory(foo);
Path hello = foo.resolve(fileName);
Files.write(hello, ImmutableList.of(text), StandardCharsets.UTF_8);

task.setFileSystem(fs);
String fileValue = task.readFile(pathString);

// Doing this just shows "fail whale: hello world!"
// fail("fail whale: " + fileValue); 

// Failure from here adds brackets
assertEquals(text, fileValue);

I get a failure like this:

org.junit.ComparisonFailure: expected:<hello world![]> but was:<hello world![
]>

If I reverse the arguments, I can see that readFile is definitely creating that new line, and it's not just my terminal truncating.

I have no idea why JUnit is showing brackets after my string at all, and am even more confused as to why a space would get added.

readFile is simply this:

public String readFile(String path) {
  try {
    return new String(Files.readAllBytes(fs.getPath(path)));
  } catch (Exception e) {
    e.printStackTrace();
    return "";
  }
}

Java: Is assertEquals(String, String) reliable? makes reference of the String being an Object , but if that is the case, an the brackets just imply Object , still really confused about that new line.

The JUnit assertEquals method puts square brackets around the part of the string where the difference occurred, to help highlight the problem for you. (Play around with assertEquals("abcde", "acedc") or the like to see it on a more intuitive example.)

In this case, it shows that one string has nothing after it, while another string has a newline at the end of it.

The Files.write documentation states:

Each line is a char sequence and is written to the file in sequence with each line terminated by the platform's line separator, as defined by the system property line.separator .

The brackets are meant to highlight where the strings are different.

In your case, there it is highlighting an unexpected newline at the end of your actual result.

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