为什么在我的String值之后有括号?

Dav*_*ein 4 java junit

我有这样的测试:

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);
Run Code Online (Sandbox Code Playgroud)

我这样失败了:

org.junit.ComparisonFailure: expected:<hello world![]> but was:<hello world![
]>
Run Code Online (Sandbox Code Playgroud)

如果我反转参数,我可以看到它readFile肯定是在创建新行,并且它不仅仅是我的终端截断.

我根本不知道为什么JUnit会在我的字符串之后显示括号,并且更加混淆为什么会添加一个空格.

readFile 就是这样:

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

Java:assertEquals(String,String)可靠吗?String作为一个参考Object,但如果是这样,括号只是暗示Object,仍然真的混淆了这一新的行.

小智 9

JUnit assertEquals方法在字符串中出现差异的部分周围放置方括号,以帮助突出显示问题.(assertEquals("abcde", "acedc")在更直观的例子中玩游戏等等.)

在这种情况下,它表明一个字符串后面没有任何内容,而另一个字符串在它的末尾有一个换行符.

Files.write文件规定:

每行都是一个char序列,并按顺序写入文件,每行由平台的行分隔符终止,由系统属性定义line.separator.