2

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.

ChopperCharles
  • 747
  • 2
  • 9
  • 19
  • Error is: System.NotSupportedException: Invalid setup on a non-virtual (overridable in VB) member: m => m.Subject – ChopperCharles May 31 '16 at 20:32
  • For properties use [Stub or SetupProperty](http://www.nudoq.org/#!/Packages/Moq/Moq/Mock(T)/M/SetupProperty(TProperty)) rather than Setup – stuartd May 31 '16 at 20:43
  • Have you seen the answers to [this question](http://stackoverflow.com/questions/6836247/how-to-create-a-minimal-dummy-x509certificate2)? They mention something called Moles that may help you. Either that or creating a test certificate, because it seems that what you are attempting to do cannot be done, as the `Subject` property is non-virtual, as you say. – Charlie Jun 01 '16 at 06:42
  • Stub doesn't exist in the mock framework, and setupProperty has the exact same problem. – ChopperCharles Jun 02 '16 at 14:47

2 Answers2

1

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.

Gilles De Vylder
  • 165
  • 3
  • 11
0

It actually can't be done. I've moved away from Moq and am went back to using accessors instead.

ChopperCharles
  • 747
  • 2
  • 9
  • 19