You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

XUnit与MSTest解密结果不一致,原因何在?

解密方法在MSTest与XUnit测试中结果不一致的原因排查

我在对以下DecryptString解密方法进行单元测试时,发现使用MSTest和XUnit执行测试得到的结果不同,希望找到问题原因:

public static string DecryptString(string cipherText)
{
    byte[] initVectorBytes = Encoding.UTF8.GetBytes(InitVector);
    byte[] cipherTextBytes = Convert.FromBase64String(cipherText);
    PasswordDeriveBytes password = new PasswordDeriveBytes(StrEncriptyPass, null);
    byte[] keyBytes = password.GetBytes(Keysize / 8);
    RijndaelManaged symmetricKey = new RijndaelManaged();
    symmetricKey.Mode = CipherMode.CBC;
    ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes);
    MemoryStream memoryStream = new MemoryStream(cipherTextBytes);
    CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
    byte[] plainTextBytes = new byte[cipherTextBytes.Length];
    int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
    memoryStream.Close();
    cryptoStream.Close();

    string result = Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);

    return result;
}

测试情况对比

  • MSTest测试结果正常:解密后能正确得到值"Testando encriptação",测试代码如下:
[TestMethod()]
public void DecryptStringTest_DecryptString_ReturnsEqual()
{
    var decryptedActual = DecryptString("r2AegGm+zAYmaRL4i+62O2IJrhcHyPsWxHoDZ7bMimI=");
    var esperado = "Testando encriptação";

    Assert.AreEqual(decryptedActual, esperado);
}
  • XUnit测试结果异常:解密后仅得到"Testando encript",缺失了"ação"部分,测试代码如下:
[Fact]
public void DecryptStringTest_DecryptString_ReturnsEqual()
{
    var decryptedActual = DecryptString("r2AegGm+zAYmaRL4i+62O2IJrhcHyPsWxHoDZ7bMimI=");
    var esperado = "Testando encriptação";

    Assert.Equal(decryptedActual, esperado);
}

调试发现的细节

调试时注意到,byte[] plainTextBytes = new byte[cipherTextBytes.Length];这一行在两个测试框架中的执行表现不同:

  • cipherTextBytes.Length在两个框架中均为32;
  • XUnit中plainTextBytes仅填充到索引15;
  • MSTest中plainTextBytes填充到索引21。

看起来XUnit似乎影响了该方法的执行逻辑。已知参数信息:Keysize=256,InitVector为16字符的字符串,StrEncriptyPass为同长度文本。

内容的提问来源于stack exchange,提问作者SanderM

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 05:18:34