c# - Mocking ControllerContext.IsChildAction throws exception in ParentActionViewContext -


i have asp.net mvc method in controller:

public actionresult update() {     if(!controllercontext.ischildaction)     {         return redirecttoaction("details","project");     }      return partialview(); } 

i mock ischildaction returns true.

var mockcontrollercontext = new mock<controllercontext>();  mockcontrollercontext.setupget(m => m.ischildaction).returns(true);  yourcontroller controller = new yourcontroller();  controller.controllercontext = mockcontrollercontext.object; 

but change somehow reflect asp.net mechanism expects property controllercontext.parentactionviewcontext not null. when return statement executed in test throws null reference because property null. can not mock because not virtual :/

any idea how inject in controller context value it?

you have use callbase = true in controllercontext moq:

var mockcontrollercontext = new mock<controllercontext> { callbase = true, }; 

this way can still setup ischildaction property callbase equal true mock of controllercontext uses real implementation of controllercontext parentactionviewcontext should there.

edit:

after short inspection of mvc-sources guess null-reference exception might caused parentactionviewcontext comes from: this.routedata.datatokens["parentactionviewcontext"] viewcontext;.

so try add fakeroutedata.datatokens["parentactionviewcontext"] = fakeviewcontext; test.

this worked me:

[testmethod] public void mytestmethod() {     // arrange     routedata fakeroutedata = new routedata();     viewcontext fakeviewcontext = new viewcontext();     fakeroutedata.datatokens["parentactionviewcontext"] = fakeviewcontext;      mock<httpcontextbase>  httpcontextstub = new mock<httpcontextbase>();     requestcontext requestcontext = new requestcontext(httpcontextstub.object, fakeroutedata);      homecontroller controller = new homecontroller();     var mockcontrollercontext = new mock<controllercontext>(requestcontext, controller) { callbase = true, };     mockcontrollercontext.setupget(m => m.ischildaction).returns(true);      controller.controllercontext = mockcontrollercontext.object;      // act     var res = controller.update();      // assert     // todo ... } 

tested system.web.mvc, version=5.2.3.0.


Comments

Popular posts from this blog

qt - Using float or double for own QML classes -

Create Outlook appointment via C# .Net -

ios - Swift Array Resetting Itself -