首页 > 解决方案 > 如何模拟 Microsoft.Practices.EnterpriseLibrary.Security.Cryptography.CryptographyManager

问题描述

我正在使用 dotnet core Standard 将一个小的 NuGet 包放在一起。

NuGet 将解析加密的 SAML 包。

我们的组织使用 Microsoft.Practices.EnterpriseLibrary.Security.Cryptography 库。

为了允许分离,我编写了代码以在其中一个类的构造函数中接受 CryptographyManager 的实例。

我正在尝试编写单元测试来测试加密字符串的解密,但不知道如何Moq使用 CryptographyManager。

单元测试项目是一个 DotNet Core 项目。

我特别是在 NuGet 中调用:

var eb = Convert.FromBase64String(_xmlString);
// Decryption occurs here
var db = _cryptographyManager.DecryptSymmetric("RijndaelManaged", eb);
_xmlString = Encoding.Unicode.GetString(db);

任何人都可以提供有关如何进行单元测试的指示吗?我会提供一些代码,虽然不知道从哪里开始......我的单元测试缺少一个大块:

[TestMethod]
public void TestThatEmployeeInformationEncryptedIsParsedCorrect()
{

    // arrange
    // NO IDEA WHAT TO DO HERE //
    CryptographyManager cryptographyManager = null;   

    EmployeeInformation expected = new EmployeeInformation
    {
        FirstName = "Test",
        LastName = "Case",
        EmployeeNumber = "0001111111",
        LanguageCode = "en",
        CountryCode = "CA",
        RequestedPage = string.Empty,
        PositionId = "POS9999999",
        Role = "EKR"
    };

    IParser p = new XMLParser(_encryptedGoodXml, cryptographyManager);

    // act
    EmployeeInformation result = p.EmployeeInformation;

    // assert
    result.Should().BeEquivalentTo(expected);
}

标签: c#unit-testing.net-coremoq.net-standard

解决方案


正如我从文档中看到的那样,它CryptographyManager是一个abstract类,因此可以很容易地模拟它,例如:

var mockCryptoManager = new Mock<CryptographyManager>();

在此之后,您必须设置您的实际代码对其进行的调用:

mockCryptoManager
    .Setup(cm => cm.DecryptSymmetric("RijndaelManaged", It.IsAny<byte[]>()))
    .Returns(/* Here you have to put the value you want the mock return with */);

然后你可以使用你的模拟:

CryptographyManager cryptographyManager = mockCryptoManager.Object;

推荐阅读