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

时间:2017-02-03 15:31:05

标签: c# .net unit-testing selenium string-comparison

我很难想到这一点。我正在编写一个单元测试,用于验证站点显示的MD5是否与文件的实际MD5相匹配。我这样做只需抓取页面显示的内容然后计算我自己的文件MD5。我使用Selenium WebDriver获取页面上的文本。

正如预期的那样,字符串显示为相同的...... 或者它似乎是

当我尝试使用Assert.AreEqualAssert.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有一堆0宽的字符。然而,这样做摆脱了md5

的后半部分

SOO ,这必须意味着他们在不同的编码中是正确的吗?但是不会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 char数组每2个字母里面有一堆随机字符

enter image description here

1 个答案:

答案 0 :(得分:4)

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

您的""不为空,实际上有一个"‌​然后是unicode 零宽度非连接器 + 零宽度空间然后{{ 1}}所以你不是用空字符串替换"而是插入其他字符。

删除并重新输入"-"或使用""