I am trying to unit test this code, but I am getting different results when using MSTest and XUnit. Why? Does anyone have any idea?
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;
}
Using MSTest it works fine and the decryptedActual variable gets this value: "Testando encriptação".
[TestMethod()]
public void DecryptStringTest_DecryptString_ReturnsEqual()
{
var decryptedActual = DecryptString("r2AegGm+zAYmaRL4i+62O2IJrhcHyPsWxHoDZ7bMimI=");
var esperado = "Testando encriptação";
Assert.AreEqual(decryptedActual, esperado);
}
But if I use XUnit, it does not retun the same result. The decryptedActual variable gets this value: "Testando encript". It is missing "ação" from the decripted string.
[Fact]
public void DecryptStringTest_DecryptString_ReturnsEqual()
{
var decryptedActual = DecryptString("r2AegGm+zAYmaRL4i+62O2IJrhcHyPsWxHoDZ7bMimI=");
var esperado = "Testando encriptação";
Assert.Equal(decryptedActual, esperado);
}
While debugging I found that this line of code:
byte[] plainTextBytes = new byte[cipherTextBytes.Length];
is the one returning different values with XUnit, but why? cipherTextBytes.Length returns 32, but plainTextBytes gets filled only until index 15 with XUnit and until 21 with STest, as we can see on the images:
XUnit Screenshot

MS Test Screenshot

Somehow XUnit is affecting the way that function is working. Keysize= 256. InitVector is a 16 character string and as StrEncriptyPass it can be text with that size.