如何模拟 HttpResponseBase.End()?
我正在使用 Moq 创建 HttpResponseBase 的模拟对象。 我需要能够测试 HttpResponseBase.End() 在我的库中被调用。 为此,我在调用之前指定了一些文本,在调用之后指定了一些文本。 然后我检查 HttpResponseBase.Output 中是否仅存在调用 End() 之前的文本。
问题是,我不知道如何模拟 HttpResponseBase.End() 以便它停止处理,就像在 ASP.NET 中那样。
public static HttpResponseBase CreateHttpResponseBase() {
var mock = new Mock<HttpResponseBase>();
StringWriter output = new StringWriter();
mock.SetupProperty(x => x.StatusCode);
mock.SetupGet(x => x.Output).Returns(output);
mock.Setup(x => x.End()) /* what do I put here? */;
mock.Setup(x => x.Write(It.IsAny<string>()))
.Callback<string>(s => output.Write(s));
return mock.Object;
}
I'm using Moq to create a mock object of HttpResponseBase. I need to be able to test that HttpResponseBase.End() was called in my library. To do this, I specify some text before the call and some text after. Then I check that only the text before the call to End() is present in HttpResponseBase.Output.
The problem is, I can't figure out how to mock HttpResponseBase.End() so that it stops processing, like it does in ASP.NET.
public static HttpResponseBase CreateHttpResponseBase() {
var mock = new Mock<HttpResponseBase>();
StringWriter output = new StringWriter();
mock.SetupProperty(x => x.StatusCode);
mock.SetupGet(x => x.Output).Returns(output);
mock.Setup(x => x.End()) /* what do I put here? */;
mock.Setup(x => x.Write(It.IsAny<string>()))
.Callback<string>(s => output.Write(s));
return mock.Object;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我有点不清楚你想要实现什么,但从你的描述来看,听起来你正在试图让你的抽象表现得像一个特定的实现。 换句话说,因为 HttpResponse.End() 有一定的行为,你希望你的 Mock 也有同样的行为吗?
一般来说,用 Moq 来做到这一点并不是特别容易,因为它没有有序期望的概念(与 RhinoMocks 不同)。 不过,有一个对此的功能请求。
您也许可以使用回调并设置 End 方法来切换确定 Mock 的任何进一步行为的标志,但这不会特别漂亮。 我正在考虑这样的事情:
然后让所有其他设置根据
end
是 true 还是 false 来进行双重实现。这将是非常丑陋的,所以我现在会认真地重新考虑我的选择。 您至少可以采取两个方向:
It is a bit unclear to me what it is you are trying to achieve, but from your description, it sounds like you are attempting to get your Abstraction to behave like a particular implementation. In other words, because HttpResponse.End() has a certain behavior, you want your Mock to have the same behavior?
In general, that is not particularly easy to do with Moq, since it has no concept of ordered expectations (unlike RhinoMocks). There is, however, a feature request for it.
You might be able to use a Callback together with setting up the End method to toggle a flag that determines any further behavior of the Mock, but it's not going to be particularly pretty. I'm thinking about something like this:
Then have all other Setups have dual implementatations based on whether
ended
is true or false.It would be pretty damn ugly, so I'd seriously reconsider my options at this point. There are at least two directions you can take: