I’m using Moq to create a Mock<HttpResponseBase> to test an FileResult I’m creating for my MVC2 application.
In the WriteFile(HttpResponseBase response) method of the FileResult, I have the following code at the end:
// Write the final output with specific encoding.
response.OutputStream.Write(output, 0, output.Length);
response.AppendHeader("Content-Encoding", encoding);
It will use utf-8 or gzip depending on the encoding from the request’s Accept-Encoding header.
So then in my test, I setup my Mock<HttpResponseBase> like so:
var mockResponse = new Mock<HttpResponseBase>();
mockResponse.Setup(r => r.OutputStream).Returns(new MemoryStream());
mockResponse.Setup(r => r.Headers).Returns(new NameValueCollection());
But when I actually check that the header has been set, Content-Encoding always returns null:
var response = mockResponse.Object;
Assert.AreEqual("utf-8", response.Headers["Content-Encoding"]);
The weird thing is that the OutputStream gets the data written to it and I can assert that it’s writing the correct value.
The odd thing is that when I actually debug the FileResult in a web project, the header is properly sent.
Does anyone have some insight to this? I can provide more code if necessary.
I ended up just mocking the
AppendHeadermethod to forcefully add the header to theHttpResponseBase‘s headers:I suspect that there is something further down inside the call of
AppendHeaderthat doesn’t like adding headers without an actualHttpResponseBasein place.If there is a better idea, feel free to suggest. Hope this helps someone in the future.