C# 如何伪造System.Web.HttpClientCertificate?
我想为WCF web服务编写单元测试。该服务使用HttpContext.Current。我已经通过向System.Web添加一个假程序集和一些代码来伪造它,如:C# 如何伪造System.Web.HttpClientCertificate?,c#,mocking,client,certificate,C#,Mocking,Client,Certificate,我想为WCF web服务编写单元测试。该服务使用HttpContext.Current。我已经通过向System.Web添加一个假程序集和一些代码来伪造它,如: [Test] public void TestMyService() { using (ShimsContext.Create()) { HttpRequest httpRequest = new HttpRequest("", "http://tempuri.org", ""); HttpContext htt
[Test]
public void TestMyService()
{
using (ShimsContext.Create())
{
HttpRequest httpRequest = new HttpRequest("", "http://tempuri.org", "");
HttpContext httpContext = new HttpContext(httpRequest, new HttpResponse(new StringWriter()));
System.Web.Fakes.ShimHttpContext.CurrentGet = () => { return httpContext; };
System.Web.Fakes.ShimHttpClientCertificate.AllInstances.IsPresentGet = (o) => { return true; };
}
}
但我的服务还需要ClientCertificate:
if (!HttpContext.Current.Request.ClientCertificate.IsPresent) // <== Exception in unit test!
throw new Exception("ClientCertificate is missing");
_clientCertificate = new X509Certificate2(HttpContext.Current.Request.ClientCertificate.Certificate);
if(!HttpContext.Current.Request.ClientCertificate.IsPresent)//我自己找到了解决方案。
因为异常来自HttpClientCertificate的构造函数,所以我也不得不伪造它。我在伪造的构造函数中什么也不做:
System.Web.Fakes.ShimHttpClientCertificate.ConstructorHttpContext = (o, httpCont) => { };
此外,为了在我的单元测试中使用HttpContext.Current.Request.ClientCertificate.certificate获得有用的客户端证书,我伪造了:
byte[] clientCertBytes = {0x30, 0x82, 0x03, ...., 0xd3};
System.Web.Fakes.ShimHttpClientCertificate.AllInstances.CertificateGet = (o) =>
{
return clientCertBytes;
};
clientCertBytes是我在调试会话中创建的X509Certificate2对象的原始数据,在调试会话中,我从文件创建了该对象(也可以从证书存储中完成)