如何使用Moq模拟HTTPcontext

时间:2012-05-17 05:16:37

标签: asp.net .net moq

我的公司有自己的SDK,其中包含以下类:

public class SharePointContext(System.Web.HttpContext context)
{

}

我如何使用Moq模拟要在参数中传递的HttpContext?来自互联网的示例使用HttpContextBase,显然它会抛出一个错误,因为你不能用抽象类分配具体的类。

任何想法?

1 个答案:

答案 0 :(得分:0)

对于最新的Moq,这样的事情应该有效。似乎Moq需要一个抽象类或接口,或者至少是一个未密封的类。所有这些都使模拟HttpContext变得困难。

//class that returns all the mock objects you need..
public static class MockHelpers
{
   public static HttpContextBase GetFakeContext()
   {
       var context = new Mock<HttpContextBase>();
       //we need these for our context 
       var request = new Mock<HttpRequestBase>();
       var response = new Mock<HttpResponseBase>();
       var session = new Mock<HttpSessionStateBase>();
       var server = new Mock<HttpServerUtilityBase>();


       context.Setup(ct => ct.Request).Returns(request.Object);
       context.Setup(ct => ct.Response).Returns(response.Object);
       context.Setup(ct => ct.Session).Returns(session.Object);
       context.Setup(ct => ct.Server).Returns(server.Object);

       return context.Object;
   }
}

然后你就这样使用它:

public class SharePointContext(MockHelpers.GetFakeContext());