HttpResponseBase.Headers在运行测试时为空 [英] HttpResponseBase.Headers are empty when running test
问题描述
我正在使用Moq创建Mock<HttpResponseBase>
来测试为我的MVC2应用程序创建的FileResult
.
I'm using Moq to create a Mock<HttpResponseBase>
to test an FileResult
I'm creating for my MVC2 application.
在FileResult
的WriteFile(HttpResponseBase response)
方法中,我在结尾处有以下代码:
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);
根据请求的Accept-Encoding
标头中的编码,它将使用utf-8
或gzip
.
It will use utf-8
or gzip
depending on the encoding from the request's Accept-Encoding
header.
所以在测试中,我像这样设置Mock<HttpResponseBase>
:
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());
但是当我实际检查是否已设置标头时,Content-Encoding
始终返回null:
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"]);
奇怪的是,OutputStream将数据写入了其中,我可以断言它正在写入正确的值.
The weird thing is that the OutputStream gets the data written to it and I can assert that it's writing the correct value.
奇怪的是,当我在Web项目中实际调试FileResult
时,标头已正确发送.
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.
推荐答案
我最终只是模拟了AppendHeader
方法,以将标题强制添加到HttpResponseBase
的标题中:
I ended up just mocking the AppendHeader
method to forcefully add the header to the HttpResponseBase
's headers:
mockResponse
.Setup(r => r.AppendHeader(It.IsAny<string>(), It.IsAny<string>()))
.Callback((string k, string v) => mockResponse.Object.Headers.Add(k, v));
我怀疑AppendHeader
的调用中是否还有其他内容,这不喜欢在没有实际的HttpResponseBase
的情况下添加标头.
I suspect that there is something further down inside the call of AppendHeader
that doesn't like adding headers without an actual HttpResponseBase
in place.
如果有更好的主意,请随时提出建议.希望这对以后的人有所帮助.
If there is a better idea, feel free to suggest. Hope this helps someone in the future.
这篇关于HttpResponseBase.Headers在运行测试时为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!