Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Moq to mock X509Certificate2?

I need to have my X509Certificate2.Subject return gibberish for code coverage in unit tests. I've tried using Moq, but it fails because Subject is not a virtual method. Is there a way to do this, or do I have to re-invent the wheel here?

          Mock<X509Certificate2> mockCert = new Mock<X509Certificate2>(contextAccessor.Certificate.RawData);
      mockCert.Setup(m=>m.Subject).Returns("kjewnr,mwnzlxkcuvlkrj,wmelq");
      mockCert.CallBase = true;

      contextAccessor.Certificate = mockCert.Object;
      authenticatorAccessor.LogAuthentication(context);

Can Moq do this? If not, are there other libraries that will work for me? Thanks.

like image 302
ChopperCharles Avatar asked Sep 11 '25 13:09

ChopperCharles


1 Answers

Old post, but since I ran into this via Google, I figured I'd mention what worked for me.

private X509Certificate2 CreateSelfSignedCertificate()
{
    var ecdsa = ECDsa.Create();
    var req = new CertificateRequest("foobar", ecdsa, HashAlgorithmName.SHA256);
    X509Certificate2 cert = req.CreateSelfSigned(DateTimeOffset.Now, DateTimeOffset.Now.AddYears(5));

    return cert;
}

Where foobar is the subject you want mocked.

like image 137
Gilles De Vylder Avatar answered Sep 13 '25 02:09

Gilles De Vylder