c# - MVC - Moq Unit Test FileContentResult (ActionResult) - NullRefernceException -


so i'm posting mvc controller, makes call repository telerik report, exports pdf. i'm having trouble unit testing , keep getting error -

system.nullreferenceexception: object reference not set instance of object.

controller

public class reportcontroller : controller {     private ipdfrepository _pdfrepository;      //dependency injection using unity.mvc5 nuget package     public reportcontroller(ipdfrepository pdfrepository)     {         _pdfrepository = pdfrepository;     }      [httppost]     [validateantiforgerytoken]     public actionresult pdfexport(pdfviewmodel model)     {         byte[] report = _pdfrepository.buildexport(model);         return file(report, "application/pdf", model.selectedreport + ".pdf");     } } 

unit test

[testmethod] public void report_pdfexport_returns_actionresult() {     //arrange     var mockrepository = new mock<ipdfrepository>();     mockrepository.setup(x => x.buildexport(it.isany<pdfviewmodel>()));      reportcontroller controller = new reportcontroller(mockrepository.object);      //act     actionresult result = controller.pdfexport(it.isany<pdfviewmodel>());      //assert     assert.isinstanceoftype(result, typeof(actionresult)); } 

now, realize has return portion of controller.

return file(report, "application/pdf", model.selectedreport + ".pdf"); 

i can change around return string, test again , work.

also, if comment out these last 2 lines of unit test,

//act //actionresult result = controller.pdfexport(it.isany<pdfviewmodel>());  //assert //assert.isinstanceoftype(result, typeof(actionresult)); 

it run without error. can't figure out how around null reference.

you not setting mock of ipdfrepository properly. needs configure going return when buildexport called. otherwise report null.

and not calling method under test valid parameter. need create concrete instance other wise model null , model.selectedreport error out.

[testmethod] public void report_pdfexport_returns_actionresult() {     //arrange     byte[] fakepdfreport = new byte[0];      var mockrepository = new mock<ipdfrepository>();     mockrepository         .setup(x => x.buildexport(it.isany<pdfviewmodel>()))         .returns(fakepdfreport);      var fakeviewmodel = new pdfviewmodel {         selectedreport = "fakereportname"         //set needed properties...     };      reportcontroller controller = new reportcontroller(mockrepository.object);      //act     actionresult result = controller.pdfexport(fakeviewmodel);      //assert     assert.isinstanceoftype(result, typeof(actionresult)); } 

Popular posts from this blog

php - How should I create my API for mobile applications (Needs Authentication) -

5 Reasons to Blog Anonymously (and 5 Reasons Not To)

Google AdWords and AdSense - A Dynamic Small Business Marketing Duo