-1

I'm currently unit testing .NET application with NUnit framework.

Some of the methods we use involve getting X509Certificate2 object as input and checking if one or more properties match certain crateria.

For example, method that check whether the thumbprint exists in a very specific list.

Thus, I need a way to mock or fake the X509Certificate2 object so that I can control what the thumbprint field will return or what are the extentions list will contain.

One way I can approach this is to create the special certificates and use them as resources in the tests project (hard coded or embedded resource).

I'm searching for a different solution, if it's even possible.

And suggestions will be greatly appreciated! Thanks in advance :)

Emilio
  • 11
  • 5
  • To unit test sealed classes or structs, I usually create a wrapper factory for this class and wrap sealed struct/class. Then wrapper and factory can be mocked, thus enabling you to test different combinations. – eocron Aug 30 '20 at 18:14
  • So basically, it's either I refactor my whole code with the new wrapper or I create the certificates and use them as resources, Correct? No other way to achieve this? – Emilio Aug 30 '20 at 19:54
  • Yes, this problem is quite often when you work with sealed classes. You should design your application taking this into consideration if you want to test different DTO combinations. – eocron Aug 30 '20 at 19:55
  • Alright, appreciate the help! – Emilio Aug 30 '20 at 20:04

1 Answers1

0

You can create wrapper around some uncontrollable sealed entity and refactor usages of this entity, so it's no longer used inside your application (in simple words, making sure there is no references to X509 at all):

public interface ICertificate
{
    //use this only when you pass it back into uncontrolled scope (other libraries, for example OAuth, HttpClient, etc)
    //this also can be hidden by internal interface and extension methods for specifying interaction with uncontrolled scopes. 
    //For example void SetCert(this HttpClient, ICertificate cert);
    X509Certificate Value {get;}
    string Thumbprint {get;}
    string Issuer {get;}
}

public interface ICertificateFactory
{
   ICertificate Create(string path);
   ICertificate Create(X509Certificate value);
   //... and other methods which corresponds to new X509Certificate, from storage or other places.
}

Then you can mock it. For other cases, such as creating HttpClient there is no way around than creating some test certificates "in flesh".

eocron
  • 6,885
  • 1
  • 21
  • 50