X509Certificate2 用于单元测试

X509Certificate2 for unit tests

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

我们使用的一些方法涉及获取 X509Certificate2 对象作为输入并检查一个或多个属性是否与特定条件匹配。

例如,检查指纹是否存在于非常具体的列表中的方法。

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

我可以解决这个问题的一种方法是创建特殊证书并将它们用作测试项目中的资源(硬编码或嵌入式资源)。

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

如有建议,我们将不胜感激! 提前致谢:)

您可以围绕一些无法控制的密封实体创建包装器并重构该实体的用法,因此它不再在您的应用程序中使用(简单来说,确保根本没有对 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.
}

那你就可以mock了。对于其他情况,例如创建 HttpClient,除了“实际”创建一些测试证书之外别无他法。