I am working on an ASP.NET MVC application and am trying to write some unit tests against controller actions, some of which manipulate properties in an HttpContext such as Session, Request.Cookies, Response.Cookies, etc. I am having trouble figuring out how to "Arrange, Act, Assert" ... I can see Arrange and Assert ... but it's hard for me to figure out how to "act" on the properties of the mocked HttpContextBase when all its properties have only getters. I canโt set anything in my mocked context from my actions with the controller ... so this is not very useful. I'm new to ridicule, so I'm sure something is missing there, but it seems logical that I can create a mock object that I can use in the context of testing controller actions, where I can actually set property values, and then later to claim that they are still what I installed them to, or something like that. What am I missing?
public static HttpContextBase GetMockHttpContext() { var requestCookies = new Mock<HttpCookieCollection>(); var request = new Mock<HttpRequestBase>(); request.Setup(r => r.Cookies).Returns(requestCookies.Object); request.Setup(r => r.Url).Returns(new Uri("http://example.org")); var responseCookies = new Mock<HttpCookieCollection>(); var response = new Mock<HttpResponseBase>(); response.Setup(r => r.Cookies).Returns(responseCookies.Object); var context = new Mock<HttpContextBase>(); context.Setup(ctx => ctx.Request).Returns(request.Object); context.Setup(ctx => ctx.Response).Returns(response.Object); context.Setup(ctx => ctx.Session).Returns(new Mock<HttpSessionStateBase>().Object); context.Setup(ctx => ctx.Server).Returns(new Mock<HttpServerUtilityBase>().Object); context.Setup(ctx => ctx.User).Returns(GetMockMembershipUser()); context.Setup(ctx => ctx.User.Identity).Returns(context.Object.User.Identity); context.Setup(ctx => ctx.Response.Output).Returns(new StringWriter()); return context.Object; }
Bob yexley
source share