asp.net mvc 3 - How should you unit test with repository classes in MVC3? -


i'm trying test on controllers data repository classes. part of repository want test:

public class newsrepository {     public ienumerable<newsitem> getnews()     {         var result = (from n in n_db.newsitems                      orderby n.id descending                      select n).take(3);         return result;     } } 

just small code how testing works. in homecontroller i've got code inside index():

    public actionresult index()     {         viewbag.message = "announcements";         newsrepository n_rep = new newsrepository();         var model = i_rep.getnews();          return view(model);     } 

i new testing explanations great. thanks.

your controller impossible unit tested in isolation because coupled repository on following line:

newsrepository n_rep = new newsrepository(); 

you have hardcoded specific implementation of repository , in unit test cannot mock it. in order should start defining abstraction on repository:

public interface inewsrepository {     ienumerable<newsitem> getnews(); } 

and have specific repository implement interface:

public class newsrepository : inewsrepository {     ... } 

ok have abstraction let's weaken coupling between data access , controller logic using abstraction:

public class newscontroller: controller {     private readonly inewsrepository repository;     public newscontroller(inewsrepository repository)     {         this.repository = repository;     }      public actionresult index()     {         viewbag.message = "announcements";         var model = this.repository.getnews();         return view(model);     }     } 

alright, have controller no longer tightly coupled specific implementation. pickup favorite mock framework , write unit test. example nsubstitute here's how unit test index action might like:

[testmethod] public void index_action_fetches_model_from_repo() {     // arrange     var repo = substitute.for<inewsrepository>();     ienumerable<newsitem> expectednews = new[] { new newsitem() };     repo.getnews().returns(expectednews);     var sut = new newscontroller(repo);      // act     var actual = sut.index();      // assert     assert.isinstanceoftype(actual, typeof(viewresult));     var viewresult = actual viewresult;     assert.areequal(expectednews, viewresult.model); } 

and that's pretty it. controller unit testable in isolation. don't need setting databases or whatever. that's not point test controller logic.


Comments

Popular posts from this blog

php - mySql Join with 4 tables -

css - Text drops down with smaller window -

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -