【问题标题】:How do I fake System.Web.HttpClientCertificate?如何伪造 System.Web.HttpClientCertificate?
【发布时间】:2013-08-20 14:00:33
【问题描述】:

我想为 WCF Web 服务编写单元测试。该服务使用 HttpContext.Current。我已经设法通过向 System.Web 添加一个 Fake Assembly 和一些代码来伪造它:

[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);

现在在标记的行中,单元测试会抛出 NullReferenceException:

结果消息:System.NullReferenceException:对象引用不 设置为对象的实例。结果堆栈跟踪:在 System.Web.HttpClientCertificate..ctor(HttpContext 上下文)在 System.Web.HttpRequest.CreateHttpClientCertificateWithAssert() 在 System.Web.HttpRequest.get_ClientCertificate() 在(我的方法)在 TestMyService()

如何为单元测试设置 ClientCertificate?我不知道如何创建一个通过 Shim 传递的 HttpClientCertificate 对象,因为没有合适的构造函数。

【问题讨论】:

    标签: c# mocking client certificate


    【解决方案1】:

    我自己找到了解决方案。 因为异常来自 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 对象的 RawData,我从文件中创建了该对象(也可以从证书存储中完成)。

    【讨论】:

      猜你喜欢
      • 2010-11-15
      • 2012-09-20
      • 1970-01-01
      • 2011-07-13
      • 2016-11-12
      • 2012-07-08
      • 2012-06-02
      • 2011-07-02
      • 2011-04-30
      相关资源
      最近更新 更多