如何解决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,除了“在肉体中”创建一些测试证书外,别无他法。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。