Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit-test an MVC controller action which depends on authentication in c#?

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?

like image 217
Mats Avatar asked Jul 09 '09 20:07

Mats


People also ask

How do you write a unit test for a controller?

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.

Is it possible to unit test an MVC application without running the controllers in an ASP NET process?

thanks! unit tests do not run in the "MVC environment." They will run within the scope of the test runner, be that nunit, resharper,....


1 Answers

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"); 
like image 162
eu-ge-ne Avatar answered Sep 30 '22 21:09

eu-ge-ne