简体   繁体   中英

How do i get the model from the mocked controller ActionResult method

I have the following:

        SiteViewModel testForm = new SiteViewModel
        {
            SiteID = 0,
            DateCreated = DateTime.Now,
            Name = "A",
        };

        SiteController controller = new SiteController(mockSiteRepository.Object);

        //// Act
        SiteViewModel result = controller.Edit(testForm); // This will not work because Edit is an ActionResult... but I want to get the model that comes out the end of the ActionResult

How do I go about getting the model from the ActionResult method so I can run tests upon it?

You have to cast the ActionResult to a ViewResult . Then you can access the Model property.

// Act
var result = controller.Edit(testForm);

// Assert
var viewResult = result as ViewResult;
Assert.That(viewResult, Is.Not.Null);

var model = viewResult.Model as SiteViewModel;
Assert.That(model, Is.Not.Null);

// do your other assertions.

See this answer for an interesting discussion of the different ActionResult types

If your Edit action only ever returns a ViewResult then you could change its method signature to indicate that. I wouldn't recommend doing this however because it will make your code more brittle, for instance if you want to change the Action's behaviour in the future.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM