相同的字符串内容但长度不同

3
我正在努力理解这个问题。我正在编写一个单元测试,用于验证网站显示的MD5是否与文件的实际MD5匹配。我通过简单地抓取页面显示的内容,然后计算自己的文件MD5来完成此操作。我使用Selenium WebDriver获取页面上的文本。
正如预期的那样,字符串显示为相同...或者看起来是相同的。
当我尝试使用Assert.AreEqual或Assert.IsTrue测试两个字符串时,无论如何比较它们都会失败。
我已经尝试了以下方法:
Assert.AreEqual(md5, md5Text); //Fails
Assert.IsTrue(md5 == md5Text); //Fails
Assert.IsTrue(String.Equals(md5, md5Text)); //Fails
Assert.IsTrue(md5.Normalize() == md5Text.Normalize()); //Fails
Assert.AreEqul(md5.Normalize(), md5Text.Normalize()); //Fails

起初,我以为这两个字符串是不同的,但是在调试器中查看它们后发现这两个字符串完全相同。 enter image description here 所以我尝试查看它们的长度,这时我才明白了原因。

enter image description here

字符串长度不同,因此我尝试对md5变量进行子字符串操作,以使其与md5Text变量的大小相匹配。我的想法是md5可能有很多零宽字符。但是这样做会去掉md5的后一半。
所以,这意味着它们处于不同的编码中,对吗?但是Normalize()不应该可以解决这个问题吗?
这是创建变量md5的方法。
string md5;
using (var stream = file.Open()) //file is a custom class with an Open() method that returns a Stream
{
    using (var generator = MD5.Create())
    {
        md5 = BitConverter.ToString(generator.ComputeHash(stream)).Replace("-", "‌​").ToLower().Trim();
    }
}

这就是md5Text变量的创建方法

//I'm using Selenium WebDrvier to grab the text from the page
var md5Element = row.FindElements(By.XPath("//span[@data-bind='text: MD5Hash']")).Where(e => e.Visible()).First();
var md5Text = md5Element.Text;

我该如何让这个测试通过?它应该是通过的(因为它们是相同的)

更新:

评论建议我将字符串转换为char []并迭代它。这是那样做的结果(http://pastebin.com/DX335wU8),以及我添加的代码。

        char[] md5Characters = md5.ToCharArray();
        char[] md5TextCharacters = md5Text.ToCharArray();

        //Use md5 length since it's bigger
        for (int i = 0; i < md5Characters.Length; i++)
        {
            System.Diagnostics.Debug.Write("md5: " + md5Characters[i]);

            if (i >= md5TextCharacters.Length)
            {
                System.Diagnostics.Debug.Write(" | Exhausted md5Text characters..");
            }
            else
            {
                System.Diagnostics.Debug.Write(" | md5Text: " + md5TextCharacters[i]);
            }
            System.Diagnostics.Debug.WriteLine("");
        }

我发现有趣的一件事是,md5字符数组中每两个字母之间都有一堆随机字符。

enter image description here


5
在调试器中查看var contents = md5.ToCharArray(),找出额外字节的位置和内容。 - Alex K.
1
如果你逐个字符地枚举两个字符串并进行比较,会发生什么情况? - alex.b
1个回答

4

.Replace("-", "‌​")

您的""并非空字符串,实际上有一个"‌​,然后是Unicode中的零宽度不连字符加上零宽度空格,再接着是",因此您并没有将"-"替换为空字符串,而是插入了其他字符。

请删除并重新输入"",或使用String.Empty


1
是的,就是这样。在IDE中尝试删除""时,我需要按两次退格键而不是四次。我已经用String.Empty替换了它,现在测试通过了。 - edkek

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接