c# - Testing viewmodel constructor arguments with Moq -


i have basic crud application written in asp.net core, example controller action looking so:

public iactionresult sheet(guid characterid) {     var character = _repository.getcharacter(characterid);     // omit validation brevity     return view("sheet", new viewmodel(character, true, true)); } 

and example unit test:

[fact] public void testsheet() {     // arrange stuff , mock setup     // act     var result = _controller.sheet(characterid) viewresult;      // assert     assert.notnull(result);      // assert viewmodel constructor called x arguments } 

other research seems suggest having mock of object, not appropriate scenario. have constructor viewmodel set couple of getter properties, seem delving realm of testing viewmodel opposed controller. controller should not care viewmodel values passed it, , in opinion neither should test - test testing controller behaves properly, , should test passing correct values. couple of getter properties achieve seems conceptually wrong.

the action tightly coupled creation of view model , can inverted

public interface iviewmodelfactory {     t createnew<t>(params object[] args) t : viewmodelbase; }  public class viewmodelfactory : iviewmodelfactory {     public t createnew<t>(params object[] args) t : viewmodelbase {         return (t)activator.createinstance(typeof(t), args);     } }  public class viewmodelbase { } 

so not responsibility of controller create/initialize view models. explicit dependency injected controller , used create view models.

public iactionresult sheet(guid characterid) {     var character = _repository.getcharacter(characterid);     // omit validation brevity     return view("sheet", _viewmodelfactory.createnew<viewmodel>(character, true, true)); } 

and desired behavior can asserted when exercised in unit tests

[fact] public void testsheet() {     // arrange stuff , mock setup     var factory = new mock<iviewmodelfactory>();     factory.setup(_ => _.createnew<viewmodel>(it.isany<object[]>()))            .returns((object[] args) =>                new viewmodel((character)args[0], (bool)args[1], (bool)args[2])            );            // act     var result = _controller.sheet(characterid) viewresult;      // assert     assert.notnull(result);      // assert viewmodel constructor called x arguments     factory.verify(_ => _.createnew<viewmodel>(it.isany<character>(), true, true), times.atleastonce()); } 

Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -