c# - How can I mock up a repository method that is being used inside the Method to test (in the model) -


i trying use case work me:

i having repository class: abcrepository having virtual method getmyvalues()

a model class: abcmodel, having method abctotest(). inside abctotest(), trying access abcrepository using ninject:

  var repo =  kernel.get<abcrepository>();      //further using repository method      var results =  repo.getmyvalues(); 

now, using following code create unittest abctotest() , mocking getmyvalues() method:

            var kernel = new moqmockingkernel();              kernel.bind<abcrepository>().tomock();               kernel.bind<abcmodel>().tomock();              var abcrepo= kernel.getmock<abcrepository>();                abcrepo.setup(repo => repo.getmyvalues()).returns("abc");  //this static method using initialize kernel object, abctotest() method using.             mvcapplication.initializeinjection(kernel);              var model= kernel.getmock<abcmodel>().object;              model.abctotest("177737"); 

when trying debug/run test, can see, getmyvalues() method call inside abctottest not returning "abc" null.

what's wrong doing implementation? suggestions , pointers highly appreciated..

thanks & regards sumeet

looks you've stumbled across service locator anti-pattern (http://blog.ploeh.dk/2010/02/03/servicelocatorisananti-pattern/)

you should change abcmodel class inject abcrepository constructor:

private readonly iabcrepository repo;  public abcmodel(iabcrepository repo) {     this.repo = repo; } 

then unit test this:

private mock<iabcrepository> mockrepo; private abcmodel model;  [setup] public void setup() {     mockrepo = new mock<iabcrepository>();      model = new abcmodel(mockrepo.object); }      [test] public void abctotest_whencalled_callsrepository {            model.abctotest("177737");      mockrepo.verify(a => a.getmyvalues(), times.once); } 

Comments