c# - How to unit test ASP.Net MVC controller that has private methods in the action? -


i having hard time wrapping head around unit testing pattern when trying test asp.net mvc controller/action.

with following code, trying write test showperson() method:

public class personcontroller : controller {     private idataaccessblock _dab;      public personcontroller()         : this(new dataaccessblock())     { }      public personcontroller(idataaccessblock dab)     {         _dab = dab;     }      public actionresult showperson(personrequestviewmodel personrequest)     {         var person = getpersonviewmodel(personrequest);         return view("person", person);     }      private personviewmodel getpersonviewmodel(personrequestviewmodel personrequest)     {         var personservice = new commondomainservice.personservice(_dab);         var dt = personservice.getpersoninfo(personrequest.id);         var person = new personviewmodel();          if (dt.rows.count == 1)         {             person.firstname = dt.rows[0]r["firstname"]);             person.lastname = dt.rows[0]["lastname"];         }         return person;     } } 

the test using (using nunit , moq):

[test] public void showperson_action_should_return_person_view() {     // arrange     string expected = "person";     mock<personrequestviewmodel> personrequestviewmodelmock = new mock<personrequestviewmodel>();     personrequestviewmodelmock.setupproperty(f => f.id, 123456);      mock<idataaccessblock> mockdab = new mock<idataaccessblock>();     personcontroller personcontroller = new personcontroller(mockdab.object);      // act     viewresult result = personcontroller.showperson(personrequestviewmodelmock.object) viewresult;      // assert     personrequestviewmodelmock.verify();     result.should().not.be.null();     if (result != null) assert.areequal(expected, result.viewname, "unexpected view name"); } 

everything seems go fine, until line if (dt.rows.count == 1) encountered. "object reference not set instance of object."

i assume there must funky way following 2 lines written:

var personservice = new commondomainservice.personservice(_dab); var dt = personservice.getpersoninfo(personrequest.id); 

but i'm not sure go here. have lot of code this. doing wrong, or there actual way test this?

thanks or pointers.

is commondomainservice.personservice kind of webservice hosted in webapplication, when running tests webapplication not running , service not accessible. ideally, controller has dependency on commondomainservice.personservice creating in private method,instead should injected controller(like dataaccess block), , mock in test method.


Comments

Popular posts from this blog

java - Run a .jar on Heroku -

java - Jtable duplicate Rows -

validation - How to pass paramaters like unix into windows batch file -