2013-10-08 165 views
1

我有一个asp.net MVC 3项目当我运行一些旧的单元测试,他们现在的“响应”死因为它是空它在我的控制器如何在Moq中模拟Response.Cookies.Add()?

Response.Cookies.Add() 

之一。我不知道如何嘲笑它来解决这个问题。

我在这里看到了几个帖子,但没有一个解决方案似乎工作,没有人谈论“饼干”。

回答

1

创建课程例如其中涵盖了这个静态功能。在代码中,您将此类添加为下一个依赖项,并将调用例如responseProvider.AddCookie()。在测试中,您可以使用模拟对象来获取此ResponseProvider

2
var responseCookies = new HttpCookieCollection(); 
var mockResponse = Mock.Of<HttpResponseBase>(r => r.Cookies == responseCookies); 
//you can use new Mock<>, and the set it up as well, but for simple setups I prefer the above syntax 

myTestController.Response = mockResponse; 
+1

'Response'属性是只读的。你需要模拟'ControllerContext'而不是。看看[这个答案](http://stackoverflow.com/a/18101855/5844190) –