ASP.NET MVC - checking a controller that returns different views, depending on the logic of the action method

my controller can return different views depending on the logic of the action method. The Create action method asks the service for some validation and persistence. If validation fails, the action method returns the same Create view. If validation and saving are performed normally, the action method returns a RedirectToAction index view. I know that getting a view name is only possible when you explicitly specify a view name, for example:

return View("Create", data);

I don’t want to hardcode the view name just because of the tests, but I can’t figure out how to find which view was returned. Is there a clean and elegant way to check which view was returned based on the logic of the action method?

By the way, here is my test code.

[TestMethod]
        public void Create_Post_Should_Return_Create_View_When_Saving_Invalid_Court() {
            var courtServiceMock = new Mock<ICourtService>();
            var userServiceMock = new Mock<IUserService>();
            courtServiceMock.Setup(x => x.Add(It.IsAny<CourtInfo>())).Returns((int?)null);
            userServiceMock.Setup(x => x.Get(It.IsAny<string>(), It.IsAny<UserLoadOptions>())).Returns(new UserInfo { Id = 1 });
            var controller = new CourtsController(courtServiceMock.Object, userServiceMock.Object);
            var controllerContextMock = new Mock<ControllerContext>();
            controllerContextMock.SetupGet(x => x.HttpContext.User.Identity.Name).Returns("admin");
            controller.ControllerContext = controllerContextMock.Object;
            var view = controller.Create(new CourtInfo()) as ViewResult;
            Assert.IsTrue(view.ViewName == "Create"); //this line is not working
        }
+3
source share
1 answer

You should check the type of the result, not the name of the view. If you redirect, the result will not be ViewResultanyway.

If you return RedirectToAction in case of an error, then you will do tests such as:

// setup for success
var result = controller.Create(new CourtInfo());

Assert.IsInstanceOfType(result, typeof(ViewResult));

Error test:

// setup for error
var result = controller.Create(new CourtInfo());

Assert.IsInstanceOfType(result, typeof(RedirectToRouteResult));
+4
source

Source: https://habr.com/ru/post/1724294/


All Articles