简体   繁体   中英

How to mock ControllerContext.IsChildAction property?

I have an ASP.Net MVC method in controller:

public ActionResult Update()
{
    if(!ControllerContext.IsChildAction)
    {
        return RedirectToAction("Details","Project");
    }

    return PartialView();
}

When I run this method on nunit tests I have false IsChildProperty. How do I mock this property to true to test other part of method? This property is readonly :/

You need to mock the ControllerContext of the controller you are testing, the IsChildAction property is virtual with getter only, you can set it to return true, the mock will generate a derived class that will override the property to return what you have setup.

For example if you are using the Moq lib:

var mockControllerContext = new Mock<ControllerContext>(); 
mockControllerContext.SetupGet(m => m.IsChildAction).Returns(true);

YourController controller = new YourController(); 
controller.ControllerContext = mockControllerContext.Object; 

More info:

https://coderwall.com/p/abwnkq/common-asp-net-mvc-controller-mocking-scenarios

Step 1) Although ControllerContext's IsChildAction is readonly, fortunatelly ControllerBase's ControllerContext property is not readonly, so you can set it freely on your test target controller.

Step 2) Fortunatelly the IsChildAction getter is virtual . This opens the possibility to mock it, or even without mocking create a descendant and override this getter to return with your choice.

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