1

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.

Brian Donovan-Smith
  • 392
  • 1
  • 5
  • 13
  • 2
    "Compile time string constants always have `"\r\n"`" [I don't think that's true](https://stackoverflow.com/q/74730551/5133585). Did you save your file with LF endings and still see this? – Sweeper May 11 '23 at 10:41
  • 100% correct. My editor was set to write "CRLF" line endings. When I used VSCode to change it to just use LF line endings, the test results changed. – Brian Donovan-Smith May 12 '23 at 02:38
  • 1
    It will be even more of a fun problem if your version control client mutates line endings on commit, and then you use CI/CD to build. :D – ProgrammingLlama May 12 '23 at 02:52

1 Answers1

3

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");
Brian Donovan-Smith
  • 392
  • 1
  • 5
  • 13