Darren Wainwright
Darren Wainwright

Reputation: 30747

How to Mock Microsoft.Practices.EnterpriseLibrary.Security.Cryptography.CryptographyManager

I am putting a small NuGet package together using dotnet core Standard.

The NuGet will parse an encrypted SAML package.

Our organization utilizes the Microsoft.Practices.EnterpriseLibrary.Security.Cryptography library.

To allow for separation I've written the code to accept an instance of CryptographyManager in the constructor of one of the classes.

I am trying to write unit tests that will test the decryption of an encrypted string but do not know how to Moq the CryptographyManager.

Unit Test project is a DotNet Core project.

I am specifically, in the NuGet, calling :

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

Can anybody offer pointers on how this can be unit tested? I would offer some code, though have no idea where to start... My Unit Test is missing a big piece:

[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);
}

Upvotes: 2

Views: 514

Answers (1)

Péter Csajtai
Péter Csajtai

Reputation: 898

As I can see from the documentation the CryptographyManager is an abstract class so it can be mocked very easily like:

var mockCryptoManager = new Mock<CryptographyManager>();

After this you have to setup the call your actual code makes on it:

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

And then you can use your mock like:

CryptographyManager cryptographyManager = mockCryptoManager.Object;

Upvotes: 4

Related Questions