HttpResponseBase.Headers在运行测试时为空 [英] HttpResponseBase.Headers are empty when running test

查看:169
本文介绍了HttpResponseBase.Headers在运行测试时为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用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.

FileResultWriteFile(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-8gzip.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆