英文:
c# Multiline string const, StringBuilder and unit tests
问题
I know why this is happening.
Compile time string constants always have "\r\n".
Runtime uses System.Environment.NewLine which is "\n" on a Mac (and probably Linux as well)
Is there a clean way to write tests that will work on both?
[Fact]
public void StringConst()
{
var expected = "" + "";
var actual = new StringBuilder()
.AppendLine()
.ToString();
Assert.Equal(expected, actual); // Fails on Mac
}
I don't really want to write;
Assert.Equal(expected, actual.ReplaceLineEndings("\r\n"));
Assert.Equal(expected, actual.Replace(Environment.NewLine, "\r\n"));
UPDATED:
Thank you to @sweeper for pointing me in the right direction.
The string constant is dependent on your editor. If your editor is set to use CRLF, then that is what the string constant will hold. If your editor uses LF for line endings, then that is what is used.
Silent and invisible problem.
英文:
I know why this is happening.
Compile time string constants always have "\r\n".
Runtime uses System.Environment.NewLine which is "\n" on a Mac (and probably Linux as well)
Is there a clean way to write tests that will work on both?
[Fact]
public void StringConst()
{
var expected = """
""";
var actual = new StringBuilder()
.AppendLine()
.ToString();
Assert.Equal(expected, actual); // Fails on Mac
}
I don't really want write;
Assert.Equal(expected, actual.ReplaceLineEndings("\r\n"));
Assert.Equal(expected, actual.Replace(Environment.NewLine, "\r\n"));
UPDATED:
Thank you to @sweeper for pointing me in the right direction.
The string constant is dependant on your editor. If your editor is set to use CRLF, then that is what the string constant will hold. If your editor uses LF for line endings, then that is what is used.
Silent and invisible problem.
答案1
得分: 3
Multiline string constants are dependent on how the .cs
file was saved, and StringBuilder.AppendLine
relies on the environment it runs in. Consistency requires always using newlines.
我的 .editorconfig 配置如下:
[*.cs]
end_of_line = crlf
因此,我编写了扩展方法,以便在字符串中添加新行。
public static StringBuilder AppendWithCRLF(this StringBuilder sb, string value) =>
sb.Append(value)
.Append("\r\n");
public static StringBuilder AppendCRLF(this StringBuilder sb) =>
sb.Append("\r\n");
英文:
As multiline string constants are dependant on how the .cs
file was saved and StringBuilder.AppendLine
is dependant on the environment it is run under, a consistent result means always being consistent with the use of newlines.
My .editorconfig has
[*.cs]
end_of_line = crlf
And I ended up writing extension methods for whenever I add a newline to a string.
public static StringBuilder AppendWithCRLF(this StringBuilder sb, string value) =>
sb.Append(value)
.Append("\r\n");
public static StringBuilder AppendCRLF(this StringBuilder sb) =>
sb.Append("\r\n");
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论