简体   繁体   English

将回车符字符串文字转换为回车符

[英]Convert carriage return string literal to carriage return

I have a data driven test in C# that verifies a function properly creates a string given an input. 我在C#中进行了数据驱动的测试,该测试可以验证函数是否正确创建了给定输入的字符串。

Code under test: 被测代码:

public static class Formatter
{
    public static String FormatWithCarriageReturn(int position)
    {
        return String.Format("#0 P{0} T1000 \r", position);
    }
}

The FormatWithCarriageReturn must return the string with the carriage return appended. FormatWithCarriageReturn 必须返回附加了回车符的字符串。

In order to test this method, I created a data driven test in MSTest that loads data from a CSV file. 为了测试此方法,我在MSTest中创建了一个数据驱动测试,该测试从CSV文件加载数据。

CSV File: CSV档案:

position, expected
1, #0 P1 T1000 \r
2, #0 P2 T1000 \r
3, #0 P3 T1000 \r
4, #0 P4 T1000 \r
5, #0 P5 T1000 \r
6, #0 P6 T1000 \r

Test Method: 测试方法:

/* Test method and data source attributes*/
public void FormattingWithCarriageReturnFormatsCorrectly()
{
    String expected = TestContext.DataRow["expected"].ToString();
    /* various setup code. */
    int requestedPosition = Convert.ToInt32(TestContext.DataRow["position"]);
    String actual = Formatter.FormatWithCarriageReturn(requestedPosition);
    Assert.AreEqual(expected, actual);
}

The problem is the TestContext.DataRow["expected"].ToString() statement will load the string literal #0 P1 T1000 \\\\r , and the Assert fails because it is comparing #0 P1 T1000 \\r with #0 P1 T1000 <- I can't get this to format correctly. 问题是TestContext.DataRow["expected"].ToString()语句将加载字符串文字#0 P1 T1000 \\\\r ,并且Assert失败,因为它正在将#0 P1 T1000 \\r#0 P1 T1000 < -我无法正确格式化。 There should be a carriage return at the end. 最后应该有一个回车符。

Is there a way to get the expected string out of the CSV file with the carriage return in place? 有没有办法在回车到位的情况下从CSV文件中获取期望的字符串? I could list the expected string in the CSV file as #0 P1 T1000 , and then do something like expected = String.Concat(expected, " \\r"); 我可以在CSV文件中将预期的字符串列为#0 P1 T1000 ,然后执行类似expected = String.Concat(expected, " \\r"); , but I'd like to keep the full expected string in the CSV file. ,但我想将完整的预期字符串保留在CSV文件中。

Edit: Here's the current Assert message that I'm getting: 编辑:这是我得到的当前断言消息:

Result1 Message: Assert.AreEqual failed. Expected:<#0 P1 T1000 \r>. Actual:<#0 P1 T1000
>.

A passing message would read 传递的消息将显示为

Result1 Message: Assert.AreEqual passed. Expected:<#0 P1 T1000 
>. Actual:<#0 P1 T1000
>.

Note that both expected and actual have the carriage return at the end. 请注意, expectedactual都在末尾有回车符。

Remove the "\\r" from the lines in the csv file and change 从csv文件中的行中删除“ \\ r”并进行更改

String expected = TestContext.DataRow["expected"].ToString();

to

String expected = TestContext.DataRow["expected"].ToString() +
    new String(new[] { (char)0x0D });

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

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