简体   繁体   English

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

[英]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. 如果我反转参数,我可以看到readFile肯定是在创建新行,并且它不仅仅是我的终端截断。

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. 我根本不知道为什么JUnit会在我的字符串之后显示括号,并且更加混淆为什么会添加一个空格。

readFile is simply this: readFile就是这样的:

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? Java:assertEquals(String,String)可靠吗? 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. 使String成为一个Object引用,但如果是这种情况,括号只是暗示Object ,仍然真的对这个新行感到困惑。

The JUnit assertEquals method puts square brackets around the part of the string where the difference occurred, to help highlight the problem for you. JUnit assertEquals方法在发生差异的字符串部分周围放置方括号,以帮助突出显示问题。 (Play around with assertEquals("abcde", "acedc") or the like to see it on a more intuitive example.) (使用assertEquals("abcde", "acedc")或类似的东西来看一个更直观的例子。)

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: Files.write文档说明:

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 . 每行都是一个char序列,并按顺序写入文件,每行由平台的行分隔符终止,由系统属性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. 在您的情况下,它会在实际结果的末尾突出显示意外的换行符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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