Pur*_*ome 5 .net asp.net-mvc moq mocking
我有以下代码,在运行时失败...
var mock = new Mock<ControllerContext>();
mock.SetupGet(x => x.HttpContext.Request
.ServerVariables["HTTP_HOST"]).Returns(domain);
Run Code Online (Sandbox Code Playgroud)
**运行时错误:不可覆盖的属性上的设置无效
我的控制器中有一些代码,需要检查用户请求/去过的域.
我不确定如何嘲笑它?有任何想法吗?
PS.我在上面的例子中使用了Moq framewoke ..所以我不确定这是否是一个问题,等等?
您无法在NameValueCollection上模拟索引器,因为它不是虚拟的.我要做的是模拟ServerVariables属性,因为那是IS虚拟的.您可以填写自己的NameValueCollection.见下文
这就是我要做的事情:
var context = new Mock<ControllerContext>();
NameValueCollection variables = new NameValueCollection();
variables.Add("HTTP_HOST", "www.google.com");
context.Setup(c => c.HttpContext.Request.ServerVariables).Returns(variables);
//This next line is just an example of executing the method
var domain = context.Object.HttpContext.Request.ServerVariables["HTTP_HOST"];
Assert.AreEqual("www.google.com", domain);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2875 次 |
| 最近记录: |