c# - Some questions on mocking EF 5 and testing repository pattern -


i've been reading bunch of articles on mocking repository pattern ef 5 , confused few things:

i have manager class, method addcat(string name);. method ensures name valid, , calls addcat(string name) on catrepository. catrepository mycontext.cats.add(new cat() { name = name });

that believe repository pattern in nutshell.

  • should pass repository manager class can later unit test it, or should testing repositories?

  • i want pass context repository can unit test it. i'd create interface imycontext not sure how ef context implement - place i'd add in auto-generated code , worry wipe it. there other way let me pass in custom context repository?

should pass repository manager class can later unit test it, or should testing repositories?

you should test each class in isolation. manager class contains actual business logic want test couple of scenarios:

  • valid name
  • invalid name
  • empty name

you want make sure catrepository.add not called when name invalid , it's called correct name when it's valid. achieve make sure manager class works interface icatrepository. in unit test use technique called mocking pass fake implementation of icatrepository manager class. mock has special functionality lets check methods called , validate arguments methods.

this implies manager should not construct catrepository itself:

// not solution public class manager {     public manager()     {         this.catrepository = new catrepository();     } } 

this way have no way of replacing catrepository mocked version. instead should use method called dependency injection:

 // seperate construction business logic  public class manager  {      public manager(icatrepository catrepository)      {          this.catrepository = catrepository;      }  } 

your catrepository not contain actual logic. can use integration tests (slower running tests use real database or other external object) make sure repositories function correctly.

i wrote blog subject around year ago explains difference between integration , unit tests , how mocking can create unit tests: unit testing, hell or heaven?

i want pass context repository can unit test it. i'd create interface imycontext not sure how ef context implement - place i'd add in auto-generated code , worry wipe it. there other way let me pass in custom context repository?

your context generated partial class. partial means class can spread on multiple .cs files. compiler merges files , outputs 1 single class it. way can have 1 .cs file autogenerated ef , 1 implements interface. this:

mycontext.cs

public partial class mycontext : objectcontext { } 

mycontextinterface.cs

public interface imycontext {}  public partial class mycontext : imycontext { } 

Comments