How to unit-test class has dependency on HttpResponse

When getting report from reporting service through  asmx web service, the proxy class needs to set some custom header to HttpResponse, work can be done, but unit-test it is not easy. Google result indicates that we can take advantage of HttpResponseBase and HttpResponseWrapper from System.Web and System.Web.Abstraction.

The class diagram looks like this:

Instead of directly depending on HttpContext.Current.Response, we need to change the dependency to HttpResponseBase class, from which both HttpResponseWrapper (in production) and HttpResponseFake (in unit-test) are derived.

Code example:

    public class ReportingServiceProxy
        private readonly HttpResponseBase _response;
        public ReportingServiceProxy()
            : this(new HttpResponseWrapper(HttpContext.Current.Response))
        public ReportingServiceProxy(HttpResponseBase httpResponse)
            _response = httpResponse;
        public FileContentResult GetReport(string reportName, ReportFormat reportFormat, IList parameters)
            // ...
            _response.AddHeader("cache-control", "must-revalidate");

    public class HttpResponseFake : HttpResponseBase
        public override void AddHeader(string name, string value)
            Console.WriteLine("Header {0} added with value: {1}", name, value);

        public void should_get_report_from_test_env()
            var reportingServiceProxy = new ReportingServiceProxy(new HttpResponseFake());


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s