X509Certificate2用于单元测试

问题描述

我目前正在使用NUnit框架进行.NET应用程序的单元测试。

我们使用的某些方法涉及获取X509Certificate2对象作为输入,并检查一个或多个属性是否与某些火山口匹配。

例如,一种检查指纹是否存在于特定列表中的方法

因此,我需要一种模拟或伪造X509Certificate2对象的方法,以便我可以控制指纹字段将返回的内容或扩展列表将包含的内容

我可以采用的一种方法是创建特殊证书,并将其用作测试项目中的资源(硬编码或嵌入式资源)。

如果可能,我正在寻找其他解决方案。

建议将不胜感激! 在此先感谢:)

解决方法

您可以围绕一些不可控制的密封实体创建包装器并重构该实体的用法,因此它不再在您的应用程序内部使用(简单地说,请确保没有对X509的引用):

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.
}

然后您可以模拟它。对于其他情况,例如创建HttpClient,除了“在肉体中”创建一些测试证书外,别无他法。