单元测试HttpApplication

Dav*_*own 12 c# asp.net unit-testing moq httpapplication

我有一个派生自HttpApplication的类,它增加了一些额外的功能.我需要对这些功能进行单元测试,这意味着我必须能够创建HttpApplication的新实例,伪造请求并检索响应对象.

我究竟如何对HttpApplication对象进行单元测试?我现在正在使用Moq,但我不知道如何设置所需的模拟对象.

Rob*_*ine 10

不幸的是,这并不是特别容易,因为HttpApplication不容易嘲笑; 没有可以模拟的接口,大多数方法都没有标记为虚拟.

我最近遇到了与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; }
        }
}
Run Code Online (Sandbox Code Playgroud)

等等

这让我模仿我自己的包装器界面.不一定是世界上最优雅的东西,但是一种非常有用的方法来模拟框架中一些不那么"可模仿"的部分.

在你匆匆忙忙地做这件事之前,值得回顾一下你所得到的,看看是否有更好的测试方法可以避免你必须包装课程.

在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();
Run Code Online (Sandbox Code Playgroud)