AppendHeader不会添加到HttpResponseBase.Headers集合中

时间:2012-07-18 23:09:09

标签: asp.net-mvc unit-testing mocking moq httpresponse

我很难在ASP.NET MVC中为自定义ActionFilter编写单元测试。

一切正常,但我的单元测试中有一种奇怪的行为。 AppendHeader似乎不会修改HttpResponseBase.Headers集合。当我调试以下代码时,我的集合中只有两个项目:"A""C"

var responseStub = new Moq.Mock<HttpResponseBase>();
responseStub.Setup(r => r.Headers)
    .Returns(new WebHeaderCollection { { "A", "A" } });

var response = responseStub.Object;

response.AppendHeader("B", "B");
response.Headers.Add(new NameValueCollection { { "C", "C" } });

有人可以对此有所了解并解释为什么会出现这种情况吗?

如果我在ActionFilter中使用AppendHeader运行网站,我就会收到标题。所以它通常有效,但正如我所说,我在我的HttpResponseBase.Headers集合中遗漏了它以进行测试。

1 个答案:

答案 0 :(得分:3)

查看您尝试调用它的HttpResponseBase.AppendHeader方法的实现实际上并不奇怪这个方法什么都不做。

public virtual void AppendHeader(string name, string value)
{
    throw new NotImplementedException();
}

如果您希望此方法执行某些操作,则必须为此定义期望:

// arrange
var responseStub = new Moq.Mock<HttpResponseBase>();
responseStub.Setup(r => r.Headers)
    .Returns(new WebHeaderCollection { { "A", "A" } });
var response = responseStub.Object;
responseStub
    .Setup(r => r.AppendHeader(It.IsAny<string>(), It.IsAny<string>()))
    .Callback<string, string>((name, value) => response.Headers.Add(new NameValueCollection { { name, value } }));

// act
response.AppendHeader("B", "B");

// assert
Assert.AreEqual(2, response.Headers.Count);