How to mock ActionExecutingContext with Moq? - asp.net-mvc

I am trying to test the following filter:
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.Filters;
namespace Hello
{
public class ValidationFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (!filterContext.ModelState.IsValid) {
filterContext.Result = new BadRequestObjectResult(filterContext.ModelState);
}
}
}
}
I am trying to mock the ActionFilterAttribute using Moq.
I am using Mvc 6.0.0-rc1
My first try:
var context = new ActionExecutingContext(
new ActionContext(Mock.Of<HttpContext>(), new RouteData(), new ActionDescriptor()),
new IFilterMetadata[] { filter, },
new Dictionary<string, object>(),
controller: new object());
But I could not override the ModelState. It looks to be readonly: https://github.com/aspnet/Mvc/blob/6.0.0-rc1/src/Microsoft.AspNet.Mvc.Abstractions/ActionContext.cs#L25
Then I tried:
var contextMock = new Mock<ActionExecutingContext>(
new ActionContext(Mock.Of<HttpContext>(), new RouteData(), new ActionDescriptor()),
new IFilterMetadata[] { filter, },
new Dictionary<string, object>());
But when I call filter.OnActionExecuting(contextMock.Object) I get the following error:
Castle.DynamicProxy.InvalidProxyConstructorArgumentsException : Can not instantiate proxy of class: Microsoft.AspNet.Mvc.Filters.ActionExecutingContext.
Could not find a constructor that would match given arguments:
Microsoft.AspNet.Mvc.ActionContext
Microsoft.AspNet.Mvc.Filters.IFilterMetadata[]
System.Collections.Generic.Dictionary`2[System.String,System.Object]
How to test a filter that uses ModelState?

I just stumbled on the same problem and solved it in this way.
[Fact]
public void ValidateModelAttributes_SetsResultToBadRequest_IfModelIsInvalid()
{
var validationFilter = new ValidationFilter();
var modelState = new ModelStateDictionary();
modelState.AddModelError("name", "invalid");
var actionContext = new ActionContext(
Mock.Of<HttpContext>(),
Mock.Of<RouteData>(),
Mock.Of<ActionDescriptor>(),
modelState
);
var actionExecutingContext = new ActionExecutingContext(
actionContext,
new List<IFilterMetadata>(),
new Dictionary<string, object>(),
Mock.Of<Controller>()
);
validationFilter.OnActionExecuting(actionExecutingContext);
Assert.IsType<BadRequestObjectResult>(actionExecutingContext.Result);
}

If someone was wondering how to do this when you inherit from IAsyncActionFilter
[Fact]
public async Task MyTest()
{
var modelState = new ModelStateDictionary();
var httpContextMock = new DefaultHttpContext();
httpContextMock.Request.Query = new QueryCollection(new Dictionary<string, StringValues> {}); // if you are reading any properties from the query parameters
var actionContext = new ActionContext(
httpContextMock,
Mock.Of<RouteData>(),
Mock.Of<ActionDescriptor>(),
modelState
);
var actionExecutingContext = new ActionExecutingContext(
actionContext,
new List<IFilterMetadata>(),
new Dictionary<string, object>(),
Mock.Of<Controller>()
)
{
Result = new OkResult() // It will return ok unless during code execution you change this when by condition
};
Mymock1.SetupGet(x => x.SomeProperty).Returns("MySomething");
Mymock2.Setup(x => x.GetSomething(It.IsAny<string>(), It.IsAny<string>())).ReturnsAsync(true);
var context = new ActionExecutedContext(actionContext, new List<IFilterMetadata>(), Mock.Of<Controller>());
await _classUnderTest.OnActionExecutionAsync(actionExecutingContext, async () => { return context; });
actionExecutingContext.Result.Should().BeOfType<OkResult>();
}

Related

Unit test for customer ActionFilterAttribute failed

The project is aspnet core 2.1 and i use customer ActionFilterAttribute as belows:
public override void OnActionExecuting(ActionExecutingContext context)
{
var descriptor = context.ActionDescriptor as ControllerActionDescriptor;
if (descriptor != null)
{
foreach (var parameter in descriptor.MethodInfo.GetParameters())
{
object args = null;
if (context.ActionArguments.ContainsKey(parameter.Name))
{
args = context.ActionArguments[parameter.Name];
}
ValidateAttributes(parameter, args, context.ModelState);
}
}
if (!context.ModelState.IsValid)
{
context.Result = new BadRequestObjectResult(context.ModelState);
}
}
and now I add a unit test code to test the filter,
[TestMethod]
public void ValidateModelAttributes_SetsResultToBadRequest_IfModelIsInvalid()
{
var validationFilter = new ValidateModelStateAttribute();
var modelState = new ModelStateDictionary();
modelState.AddModelError("name", "invalid");
var actionDescriptor = new ActionDescriptor();
var actionContext = new ActionContext(
Mock.Of<HttpContext>(),
Mock.Of<RouteData>(),
Mock.Of<ActionDescriptor>(),
modelState
);
var actionExecutingContext = new ActionExecutingContext(
actionContext,
new List<IFilterMetadata>(),
new Dictionary<string, object>() { { "1", "1" } },
Mock.Of<Controller>()
);
validationFilter.OnActionExecuting(actionExecutingContext);
Assert.IsNotNull(actionExecutingContext.Result);
}
but the descriptor always return null:
var descriptor = context.ActionDescriptor as ControllerActionDescriptor;
Can you help me to fix the unit test code?
but the descriptor always return null`,
that is because in the test a Mock.Of<ActionDescriptor>() which will be a ActionDescriptor is used, but the subject under test casts to ControllerActionDescriptor, which the mock is not, and thus null.
Use the appropriate mock
//...omitted for brevity
var actionContext = new ActionContext(
Mock.Of<HttpContext>(),
Mock.Of<RouteData>(),
Mock.Of<ControllerActionDescriptor>(),
modelState
);
//...omitted for brevity
You would still need to setup the mock so that the accessed members behave as expected when exercising the test

signalR send partial view result string via hub

I need to be able to return partial view as string in my MVC app via signalR. I'm using hubs.
I'm using the following method to return a partial view string (from here):
public static string RenderPartialView(string controllerName, string partialView, object model)
{
var context = httpContextBase as HttpContextBase;
var routes = new RouteData();
routes.Values.Add("controller", controllerName);
var requestContext = new RequestContext(context, routes);
string requiredString = requestContext.RouteData.GetRequiredString("controller");
var controllerFactory = ControllerBuilder.Current.GetControllerFactory();
var controller = controllerFactory.CreateController(requestContext, requiredString) as ControllerBase;
controller.ControllerContext = new ControllerContext(context, routes, controller);
var ViewData = new ViewDataDictionary();
var TempData = new TempDataDictionary();
ViewData.Model = model;
using (var sw = new StringWriter())
{
var viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, partialView);
var viewContext = new ViewContext(controller.ControllerContext, viewResult.View, ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
In order for this method to work I need HttpContext.Current therefore in my OnConnected (I noticed that this always exists) I set it like so:
public class TaskActionStatus : Hub
{
private static HttpContextBase httpContextBase;
...
public override Task OnConnected()
{
httpContextBase = new HttpContextWrapper(HttpContext.Current) as HttpContextBase;
...
and then I use it in my RenderPartialView method:
var context = httpContextBase as HttpContextBase;
This way I always have access to current HttpContext. However, I noticed that sometimes my static copy of HttpContext is null. Why is that?.
What's the best approach here?
Is there a way to render partial view without HttpContext?
I used fake http context to generate view:
public static string GetRazorViewAsString(object model, string filePath)
{
HttpContext httpContext = MockHelper.FakeHttpContext();
var st = new StringWriter();
var context = new HttpContextWrapper(httpContext);
var routeData = new RouteData();
var controllerContext = new ControllerContext(new RequestContext(context, routeData), new FakeController());
var razor = new RazorView(controllerContext, filePath, null, false, null);
razor.Render(
new ViewContext(controllerContext, razor, new ViewDataDictionary(model), new TempDataDictionary(), st),
st);
return st.ToString();
}
#endregion
}
public class FakeController : Controller
{
}
public class MockHelper
{
#region Public Methods and Operators
public static HttpContext FakeHttpContext()
{
var httpRequest = new HttpRequest(string.Empty, "http://novomatic/", string.Empty);
var stringWriter = new StringWriter();
var httpResponce = new HttpResponse(stringWriter);
var httpContext = new HttpContext(httpRequest, httpResponce);
var sessionContainer = new HttpSessionStateContainer(
"id",
new SessionStateItemCollection(),
new HttpStaticObjectsCollection(),
10,
true,
HttpCookieMode.AutoDetect,
SessionStateMode.InProc,
false);
httpContext.Items["AspSession"] =
typeof(HttpSessionState).GetConstructor(
BindingFlags.NonPublic | BindingFlags.Instance,
null,
CallingConventions.Standard,
new[] { typeof(HttpSessionStateContainer) },
null).Invoke(new object[] { sessionContainer });
return httpContext;
}
#endregion
}

How do you mock the session object collection using Moq

I am using shanselmann's MvcMockHelper class to mock up some HttpContext stuff using Moq but the issue I am having is being able to assign something to my mocked session object in my MVC controller and then being able to read that same value in my unit test for verification purposes.
My question is how do you assign a storage collection to the mocked session object to allow code such as session["UserName"] = "foo" to retain the "foo" value and have it be available in the unit test.
I started with Scott Hanselman's MVCMockHelper, added a small class and made the modifications shown below to allow the controller to use Session normally and the unit test to verify the values that were set by the controller.
/// <summary>
/// A Class to allow simulation of SessionObject
/// </summary>
public class MockHttpSession : HttpSessionStateBase
{
Dictionary<string, object> m_SessionStorage = new Dictionary<string, object>();
public override object this[string name]
{
get { return m_SessionStorage[name]; }
set { m_SessionStorage[name] = value; }
}
}
//In the MVCMockHelpers I modified the FakeHttpContext() method as shown below
public static HttpContextBase FakeHttpContext()
{
var context = new Mock<HttpContextBase>();
var request = new Mock<HttpRequestBase>();
var response = new Mock<HttpResponseBase>();
var session = new MockHttpSession();
var server = new Mock<HttpServerUtilityBase>();
context.Setup(ctx => ctx.Request).Returns(request.Object);
context.Setup(ctx => ctx.Response).Returns(response.Object);
context.Setup(ctx => ctx.Session).Returns(session);
context.Setup(ctx => ctx.Server).Returns(server.Object);
return context.Object;
}
//Now in the unit test i can do
AccountController acct = new AccountController();
acct.SetFakeControllerContext();
acct.SetBusinessObject(mockBO.Object);
RedirectResult results = (RedirectResult)acct.LogOn(userName, password, rememberMe, returnUrl);
Assert.AreEqual(returnUrl, results.Url);
Assert.AreEqual(userName, acct.Session["txtUserName"]);
Assert.IsNotNull(acct.Session["SessionGUID"]);
It's not perfect but it works enough for testing.
Using Moq 3.0.308.2 here is an example of my account controller setup in my unit test:
private AccountController GetAccountController ()
{
.. setup mocked services..
var accountController = new AccountController (..mocked services..);
var controllerContext = new Mock<ControllerContext> ();
controllerContext.SetupGet(p => p.HttpContext.Session["test"]).Returns("Hello World");
controllerContext.SetupGet(p => p.HttpContext.User.Identity.Name).Returns(_testEmail);
controllerContext.SetupGet(p => p.HttpContext.Request.IsAuthenticated).Returns(true);
controllerContext.SetupGet(p => p.HttpContext.Response.Cookies).Returns(new HttpCookieCollection ());
controllerContext.Setup (p => p.HttpContext.Request.Form.Get ("ReturnUrl")).Returns ("sample-return-url");
controllerContext.Setup (p => p.HttpContext.Request.Params.Get ("q")).Returns ("sample-search-term");
accountController.ControllerContext = controllerContext.Object;
return accountController;
}
then within your controller method the following should return "Hello World"
string test = Session["test"].ToString ();
I've made a slightly more elaborate Mock than the answer posted by #RonnBlack
public class HttpSessionStateDictionary : HttpSessionStateBase
{
private readonly NameValueCollection keyCollection = new NameValueCollection();
private readonly Dictionary<string, object> _values = new Dictionary<string, object>();
public override object this[string name]
{
get { return _values.ContainsKey(name) ? _values[name] : null; }
set { _values[name] = value; keyCollection[name] = null;}
}
public override int CodePage
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
public override HttpSessionStateBase Contents
{
get { throw new NotImplementedException(); }
}
public override HttpCookieMode CookieMode
{
get { throw new NotImplementedException(); }
}
public override int Count
{
get { return _values.Count; }
}
public override NameObjectCollectionBase.KeysCollection Keys
{
get { return keyCollection.Keys; }
}
public Dictionary<string, object> UnderlyingStore
{
get { return _values; }
}
public override void Abandon()
{
_values.Clear();
}
public override void Add(string name, object value)
{
_values.Add(name, value);
}
public override void Clear()
{
_values.Clear();
}
public override void CopyTo(Array array, int index)
{
throw new NotImplementedException();
}
public override bool Equals(object obj)
{
return _values.Equals(obj);
}
public override IEnumerator GetEnumerator()
{
return _values.GetEnumerator();
}
public override int GetHashCode()
{
return (_values != null ? _values.GetHashCode() : 0);
}
public override void Remove(string name)
{
_values.Remove(name);
}
public override void RemoveAll()
{
_values.Clear();
}
public override void RemoveAt(int index)
{
throw new NotImplementedException();
}
public override string ToString()
{
return _values.ToString();
}
public bool Equals(HttpSessionStateDictionary other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return Equals(other._values, _values);
}
}
I just found a nice example of how the Oxite team fakes their HttpSessionState and maintains a SessionStateItemCollection collection within that fake. This should work just as well as a moq in my case.
EDIT:
URL for this example is http://oxite.codeplex.com/sourcecontrol/changeset/view/33871?projectName=oxite#388065
I think you can set an expectation on the mock with a specific value it should return whatever. Mocks are not used as actual fakes but rather things that you can assert behavior on.
It sounds like you are actually looking for an adapter that you can wrap around the session that you can supply a different implementation during tests and during runtime it would return HttpContext Session items?
Does this make sense?
Thank you, #RonnBlack for your solution! In my case, I kept getting this exception because Session.SessionID was null:
System.NotImplementedException was unhandled by user code
HResult=-2147467263
Message=The method or operation is not implemented.
Source=System.Web
StackTrace:
at System.Web.HttpSessionStateBase.get_SessionID()
To solve this problem I implement #RonnBlack's code this way using the Moq Mock<HttpSessionStateBase> instead of his MockHttpSession:
private readonly MyController controller = new MyController();
[TestFixtureSetUp]
public void Init()
{
var session = new Mock<HttpSessionStateBase>();
session.Setup(s => s.SessionID).Returns(Guid.NewGuid().ToString());
var request = new Mock<HttpRequestBase>();
var response = new Mock<HttpResponseBase>();
var server = new Mock<HttpServerUtilityBase>();
// Not working - IsAjaxRequest() is static extension method and cannot be mocked
// request.Setup(x => x.IsAjaxRequest()).Returns(true /* or false */);
// use this
request.SetupGet(x => x.Headers).Returns(
new System.Net.WebHeaderCollection
{
{"X-Requested-With", "XMLHttpRequest"}
});
var context = new Mock<HttpContextBase>();
//context
context.Setup(ctx => ctx.Request).Returns(request.Object);
context.Setup(ctx => ctx.Response).Returns(response.Object);
context.Setup(ctx => ctx.Session).Returns(session.Object);
context.Setup(ctx => ctx.Server).Returns(server.Object);
context.SetupGet(x => x.Request).Returns(request.Object);
context.SetupGet(p => p.Request.Url).Returns(new Uri("http://www.mytesturl.com"));
var queryString = new NameValueCollection { { "code", "codeValue" } };
context.SetupGet(r => r.Request.QueryString).Returns(queryString);
controller.ControllerContext = new ControllerContext(context.Object, new RouteData(), controller);
}
For details, please see http://weblogs.asp.net/gunnarpeipman/using-moq-to-mock-asp-net-mvc-httpcontextbase
Just for Session easier way is to create Session object in parent class and use it like this
public class DalBl : IDalBl
{
public dynamic Session
{
get { return HttpContext.Current.Session; }
}
}
and in unitTest
var session = new Dictionary<string, object>();
var moq = new Moq.Mock<IDalBl>();
moq.Setup(d => d.Session).Returns(session);

Unit testing in asp.net MVC, how do I mock a page request?

How do I mock a page request for a .net MVC page?
Using RhinoMocks:
var httpContext = MockRepository.GenerateMock<HttpContextBase>();
var httpRequest = MockRepository.GenerateMock<HttpRequestBase>();
httpContext.Expect( c => c.Request ).Return( httpRequest ).Repeat.Any();
... set up expectations on request...
var controller = new MyController();
controller.ControllerContext = new ControllerContext( httpContext,
new RouteData(),
controller );
...invoke action, check assertions...
httpContext.VerifyAllExpectations();
httpRequest.VerifyAllExpectations();
Using Moq:
var request = new Mock<HttpRequestBase>(MockBehavior.Strict);
request.Setup(x => x.ApplicationPath).Returns("/");
request.Setup(x => x.Url).Returns(new Uri("http://localhost/home"));
request.Setup(x => x.ServerVariables).Returns(new System.Collections.Specialized.NameValueCollection());
var context = new Mock<HttpContextBase>(MockBehavior.Strict);
context.SetupGet(x => x.Request).Returns(request.Object);
var controller = new YourController();
controller.ControllerContext = new ControllerContext(context.Object, new RouteData(), controller);
Manually (because I hate Mocking frameworks that require 8 lines of setup per test)
// in some common location, only once
public class MockHttpContext : HttpContextBase
{
public MockHttpRequest m_request = new MockHttpRequest();
public MockHttpResponse m_response = new MockHttpResponse();
public override HttpRequestBase Request
{ get { return m_request; } }
public override HttpResponseBase Response
{ get { return m_response; } }
}
public class MockHttpRequest : HttpRequestBase
{
// override whatever bits you want (eg cookies)
}
public class MockHttpResponse : HttpResponseBase
{
// override whatever bits you want (eg cookies)
}
// in your specific test
controller = new YourController {
ControllerContext = new ControllerContext { HttpContext = new MockHttpContext() }
};

Mocking Asp.net-mvc Controller Context

So the controller context depends on some asp.net internals. What are some ways to cleanly mock these up for unit tests? Seems like its very easy to clog up tests with tons of setup when I only need, for example, Request.HttpMethod to return "GET".
I've seen some examples/helpers out on the nets, but some are dated. Figured this would be a good place to keep the latest and greatest.
I'm using latest version of rhino mocks
Using MoQ it looks something like this:
var request = new Mock<HttpRequestBase>();
request.Expect(r => r.HttpMethod).Returns("GET");
var mockHttpContext = new Mock<HttpContextBase>();
mockHttpContext.Expect(c => c.Request).Returns(request.Object);
var controllerContext = new ControllerContext(mockHttpContext.Object
, new RouteData(), new Mock<ControllerBase>().Object);
I think the Rhino Mocks syntax is similar.
Here is a sample unit test class using MsTest and Moq which mocks HttpRequest and HttpResponse objects. (.NET 4.0, ASP.NET MVC 3.0 )
Controller action get value from request and sets http header in response objects. Other http context objects could be mocked up in similar way
[TestClass]
public class MyControllerTest
{
protected Mock<HttpContextBase> HttpContextBaseMock;
protected Mock<HttpRequestBase> HttpRequestMock;
protected Mock<HttpResponseBase> HttpResponseMock;
[TestInitialize]
public void TestInitialize()
{
HttpContextBaseMock = new Mock<HttpContextBase>();
HttpRequestMock = new Mock<HttpRequestBase>();
HttpResponseMock = new Mock<HttpResponseBase>();
HttpContextBaseMock.SetupGet(x => x.Request).Returns(HttpRequestMock.Object);
HttpContextBaseMock.SetupGet(x => x.Response).Returns(HttpResponseMock.Object);
}
protected MyController SetupController()
{
var routes = new RouteCollection();
var controller = new MyController();
controller.ControllerContext = new ControllerContext(HttpContextBaseMock.Object, new RouteData(), controller);
controller.Url = new UrlHelper(new RequestContext(HttpContextBaseMock.Object, new RouteData()), routes);
return controller;
}
[TestMethod]
public void IndexTest()
{
HttpRequestMock.Setup(x => x["x"]).Returns("1");
HttpResponseMock.Setup(x => x.AddHeader("name", "value"));
var controller = SetupController();
var result = controller.Index();
Assert.AreEqual("1", result.Content);
HttpRequestMock.VerifyAll();
HttpResponseMock.VerifyAll();
}
}
public class MyController : Controller
{
public ContentResult Index()
{
var x = Request["x"];
Response.AddHeader("name", "value");
return Content(x);
}
}
Here's a snippet from Jason's link. Its the same as Phil's method but uses rhino.
Note: mockHttpContext.Request is stubbed to return mockRequest before mockRequest's internals are stubbed out. I believe this order is required.
// create a fake web context
var mockHttpContext = MockRepository.GenerateMock<HttpContextBase>();
var mockRequest = MockRepository.GenerateMock<HttpRequestBase>();
mockHttpContext.Stub(x => x.Request).Return(mockRequest);
// tell the mock to return "GET" when HttpMethod is called
mockRequest.Stub(x => x.HttpMethod).Return("GET");
var controller = new AccountController();
// assign the fake context
var context = new ControllerContext(mockHttpContext,
new RouteData(),
controller);
controller.ControllerContext = context;
// act
...
The procedure for this seems to have changed slightly in MVC2 (I'm using RC1). Phil Haack's solution doesn't work for me if the action requires a specific method ([HttpPost], [HttpGet]). Spelunking around in Reflector, it looks like the method for verifying these attributes has changed. MVC now checks request.Headers, request.Form, and request.QueryString for a X-HTTP-Method-Override value.
If you add mocks for these properties, it works:
var request = new Mock<HttpRequestBase>();
request.Setup(r => r.HttpMethod).Returns("POST");
request.Setup(r => r.Headers).Returns(new NameValueCollection());
request.Setup(r => r.Form).Returns(new NameValueCollection());
request.Setup(r => r.QueryString).Returns(new NameValueCollection());
var mockHttpContext = new Mock<HttpContextBase>();
mockHttpContext.Expect(c => c.Request).Returns(request.Object);
var controllerContext = new ControllerContext(mockHttpContext.Object, new RouteData(), new Mock<ControllerBase>().Object);
Or you can do this with Typemock Isolator with no need to send in a fake controller at all:
Isolate.WhenCalled(()=>HttpContext.Request.HttpMethod).WillReturn("Get");
i've finished with this spec
public abstract class Specification <C> where C: Controller
{
protected C controller;
HttpContextBase mockHttpContext;
HttpRequestBase mockRequest;
protected Exception ExceptionThrown { get; private set; }
[SetUp]
public void Setup()
{
mockHttpContext = MockRepository.GenerateMock<HttpContextBase>();
mockRequest = MockRepository.GenerateMock<HttpRequestBase>();
mockHttpContext.Stub(x => x.Request).Return(mockRequest);
mockRequest.Stub(x => x.HttpMethod).Return("GET");
EstablishContext();
SetHttpContext();
try
{
When();
}
catch (Exception exc)
{
ExceptionThrown = exc;
}
}
protected void SetHttpContext()
{
var context = new ControllerContext(mockHttpContext, new RouteData(), controller);
controller.ControllerContext = context;
}
protected T Mock<T>() where T: class
{
return MockRepository.GenerateMock<T>();
}
protected abstract void EstablishContext();
protected abstract void When();
[TearDown]
public virtual void TearDown()
{
}
}
and the juice is here
[TestFixture]
public class When_invoking_ManageUsersControllers_Update :Specification <ManageUsersController>
{
private IUserRepository userRepository;
FormCollection form;
ActionResult result;
User retUser;
protected override void EstablishContext()
{
userRepository = Mock<IUserRepository>();
controller = new ManageUsersController(userRepository);
retUser = new User();
userRepository.Expect(x => x.GetById(5)).Return(retUser);
userRepository.Expect(x => x.Update(retUser));
form = new FormCollection();
form["IdUser"] = 5.ToString();
form["Name"] = 5.ToString();
form["Surename"] = 5.ToString();
form["Login"] = 5.ToString();
form["Password"] = 5.ToString();
}
protected override void When()
{
result = controller.Edit(5, form);
}
[Test]
public void is_retrieved_before_update_original_user()
{
userRepository.AssertWasCalled(x => x.GetById(5));
userRepository.AssertWasCalled(x => x.Update(retUser));
}
}
enjoy
I find that long mocking procedure to be too much friction.
The best way we have found - using ASP.NET MVC on a real project - is to abstract the HttpContext to an IWebContext interface that simply passes through. Then you can mock the IWebContext with no pain.
Here is an example

Resources