0 votes
by (220 points)

Hi,
I would like to create a Moq of a Certificate class for my unit tests but this class is sealed, does not have an interface(I see IAsn1Node which cannot be used) and does not have any virtual methods.

I am not also able to instantiate a Certificate object in memory without touching IO and a certificate store via code.

Is there a way to do it?
Thanks

1 Answer

0 votes
by (148k points)

Hi, there are several ways to approach this:

1) You could generate (or copy&paste from Visual Studio's metadata-to-code view) an ICertificate interface from the Certificate class, along with a proxy class that converts all calls to Certificate calls (a duck typing implementation might help with that).

2) You can generate custom certificates in your unit tests using CertificateIssuer API.

3) You can instantiate a Certificate object in memory from a byte array. Or from a string that has been copy&pasted from a certificate file, like this:

string encodedCertData = @"
-----BEGIN CERTIFICATE-----
MIIH0TCCBrmgAwIBAgIQDCSwHjszVRQ0ymQMGQqyezANBgkqhkiG9w0BAQsFADB1
MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3
d3cuZGlnaWNlcnQuY29tMTQwMgYDVQQDEytEaWdpQ2VydCBTSEEyIEV4dGVuZGVk
IFZhbGlkYXRpb24gU2VydmVyIENBMB4XDTE2MTAyMTAwMDAwMFoXDTE5MDEwNDEy
MDAwMFowgeIxHTAbBgNVBA8MFFByaXZhdGUgT3JnYW5pemF0aW9uMRMwEQYLKwYB
BAGCNzwCAQMTAkNaMREwDwYDVQQFEwg2Mzk3ODI5NjEaMBgGA1UECQwRQ2hhYmVy
c2vDoSA0ODgvNDcxDjAMBgNVBBETBTE4MjAwMQswCQYDVQQGEwJDWjEOMAwGA1UE
CBMFUHJhaGExEDAOBgNVBAcTB1ByYWhhIDgxGTAXBgNVBAoMEFJFQkVYIMSMUiBz
LnIuby4xCzAJBgNVBAsTAklUMRYwFAYDVQQDEw13d3cucmViZXgubmV0MIIBIjAN
BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxAY8Z/5B0TUpmLlV214wTm+53Dr5
s3TKp4mypwEkl64pFsaIFR1xGjU8KKZ9A4RQhglagD+sXrvl8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BAAAAFX57aNpgAA
BAMARjBEAiBGoTRcOxJe/neacH35t5reWTYxdBejWZeBniYIALLKCAIgKdMfr04J
uDaj3027SRR4eZ17dZUuCovV9IsXuFHTvrsAdgBo9pj4H2SCvjqM7rkoHUz8cVFd
Z5PURNEKZ6y7T0/7xAAAAVfnto2eAAAEAwBHMEUCIDfVvpOkY5JiFTwKllyW5GfR
QsvQ5tfe60akB0Sbt2DzAiEAwB5PTWgVGAqRrEUjUIOjhZeq+8GLAkfJMD67rsmJ
AgUAdgBWFAaaL9fC7NP14b1Esj7HRna5vJkRXMDvlJhV1onQ3QAAAVfnto39AAAE
AwBHMEUCIQDi8zx0l8SiJKl3r+UXIpFadWU9oSxDaL50ZaylG8o2aQIgP1OGBBai
YXcrnm3Vsxl2BOiPhzqS+5KDFtH7Ws8zqxMAdQDuS723dc5guuFCaR+r4Z5mow9+
X7By2IMAxHuJeqj9ywAAAVfntpAdAAAEAwBGMEQCIGbMdxTzGzQ/cV4O5Sh9b6j/
Myq9ImdWfoHGiirc7Ya/AiBSWxUEXn/xoNuAPBHkAl/Vvc74FJDfM9qBpM44P0rU
bzANBgkqhkiG9w0BAQsFAAOCAQEAvfAA8MX7NYPBZ0oQca43U8l8TFaZ6zYQN4Nb
iR4bpRcmi5KmniaahjcAWM6VtbDJDIp4Tkep8AVw2h7TRIqi7wGHzo9wIaMpGkEH
xy1sMNCQIikKtTehzIX8Upo+AJ0pgsVRIxhFe6hksunFS0zkqGOcFTNiGUgm9/jn
uUbXTTMDzhZ+TNO/fm4ZnatFvI8ll0+23K8UHowt128QEiqZ6/3PBNIVS/pp2JnM
ydJFPmZuQQv5sr7HOVI2chHNj1a8AvubRknAIzMzKkLBrXHKCFuA/pu+INwPAVuc
1u+tpQWguT3i0aC4HYaWNSVXg7tT/3UxtGHaMg2IIcz3icjq0g==
-----END CERTIFICATE-----
";

byte[] certData = Encoding.ASCII.GetBytes(encodedCertData);
var certificate = new Certificate(certData);
...
by (220 points)
I will go with option 3, thanks
...