I'd like to write (in c#) a unit-test for an MVC controller action which might return one view or the other, depending on whether the request is authenticated. How can this be done?
Writing a Unit Test for REST Controller First, we need to create Abstract class file used to create web application context by using MockMvc and define the mapToJson() and mapFromJson() methods to convert the Java object into JSON string and convert the JSON string into Java object.
thanks! unit tests do not run in the "MVC environment." They will run within the scope of the test runner, be that nunit, resharper,....
You can mock your Request. Something like this (Moq using):
var request = new Mock<HttpRequestBase>(); request.SetupGet(x => x.IsAuthenticated).Returns(true); // or false var context = new Mock<HttpContextBase>(); context.SetupGet(x => x.Request).Returns(request.Object); var controller = new YourController(); controller.ControllerContext = new ControllerContext(context.Object, new RouteData(), controller); // test ViewResult viewResult = (ViewResult)controller.SomeAction(); Assert.True(viewResult.ViewName == "ViewForAuthenticatedRequest");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With