我有一个派生自 HttpApplication 的类,它添加了一些额外的功能。我已经到了需要对这些功能进行单元测试的地步,这意味着我必须能够创建 HttpApplication 的新实例、伪造请求并检索响应对象。
我该如何对 HttpApplication 对象进行单元测试?我目前正在使用 Moq,但我不知道如何设置所需的模拟对象。
最佳答案
不幸的是,这并不是特别容易做到,因为 HttpApplication 不适合很容易地进行模拟;没有可模拟的接口(interface),并且大多数方法未标记为虚拟。
我最近遇到了与 HttpRequest 和 HttpWebResponse 类似的问题。最后,我寻求的解决方案是为我想使用的方法创建一个直接的“直通”包装器:
public class HttpWebRequestWrapper : IHttpWebRequestWrapper
{
private HttpWebRequest httpWebRequest;
public HttpWebRequestWrapper(Uri url)
{
this.httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
}
public Stream GetRequestStream()
{
return this.httpWebRequest.GetRequestStream();
}
public IHttpWebResponseWrapper GetResponse()
{
return new HttpWebResponseWrapper(this.httpWebRequest.GetResponse());
}
public Int64 ContentLength
{
get { return this.httpWebRequest.ContentLength; }
set { this.httpWebRequest.ContentLength = value; }
}
public string Method
{
get { return this.httpWebRequest.Method; }
set { this.httpWebRequest.Method = value; }
}
public string ContentType
{
get { return this.httpWebRequest.ContentType; }
set { this.httpWebRequest.ContentType = value; }
}
}
等等等等
这让我可以模拟我自己的包装器接口(interface)。不一定是世界上最优雅的东西,但却是一种非常有用的方法,可以模拟出框架中一些不太“可模拟”的部分。
不过,在您匆匆忙忙地去做这件事之前,有必要回顾一下您所拥有的,看看是否有更好的测试方法可以避免您必须包装类。
对于 HttpWebRequest、HttpApplication 等,通常没有恕我直言。
为了在 mock 中设置这个包装器(使用我上面的 HttpWebRequest 示例),你然后用 Moq 做这样的事情:
var mockWebRequest = new Mock<IHttpWebRequestWrapper>();
mockWebRequest.SetupSet<string>(c => c.Method = "POST").Verifiable();
mockWebRequest.SetupSet<string>(c => c.ContentType = "application/x-www-form-urlencoded").Verifiable();
mockWebRequest.SetupSet<int>(c => c.ContentLength = 0).Verifiable();
关于c# - 对 HttpApplication 进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1182338/