c# - RhinoMocks stubs with simplified implementation, Try-method pattern -


i want mock quite huge repository rhinomocks, purpose of implementing huge , changing interface, instead of using visualstudio's "implement interface" default implementation (which requires mocks updated interface change , causes lot of junk code).

i use stubs, haven't found out how override mocked default methods, except defining every possible input value. bad when using bool tryget(key, out value) pattern , when need default behaviour besides, if key not found (here: return false/null, in other cases: throw exception).

is there way implement method forwarding in rhinomocks?

public interface imyrepository {     // implemented database access     bool trygetnamebyid(int id, out string name);      // more... }  // within other class:  public void setupmockrepository() {     idictionary<int, string> namesbyids = new dictionary<int, string>()      //create , fill mock values      var mockrep = new mockrepository()     var repstub = mockrep.stub<imyrepository>()       // this, forward inner calls,     // without defining expected input values     var repstub.stub(r => r.trygetnamebyid(int id, out string name)         .outref((id) => (namesbyids.trygetvalue(id, out name) ? name : null))         .return((id) => namesbyids.containskey(id))); } 

edit:

i tried delegate now, looks better, still has problems:

private delegate bool tryget<tkey, tvalue>(tkey key, out tvalue value);  public void setupmockrepository() {     // code above omitted      string outname;     _stub.stub(r=>r.trygetnamebyid(0, out outname))         .ignorearguments()         .do(new tryget<int,string>(namesbyids.trygetvalue)) } 

this accepted, when run it, invalidoperationexception: "previous method 'trygetvalue(123)' requires return value or exception throw"

you can make own fake objects. mix of , partial mocks, should gain maximum of flexibility.

public interface imyrepository {     bool trygetnamebyid(int id, out string name); }  public class fakerepository : imyrepository {     // public on purpose, testing after     public readonly dictionary<int, string> namebyids = new dictionary<int, string>();      // important make methods/properties virtual part of interface implementation     public virtual bool trygetnamebyid(int id, out string name)     {         return this.namebyids.trygetvalue(id, out name);     } } 

your setup become then:

public void setup() {     var mock = mockrepository.generatepartialmock<fakerepository>();     mock.namebyids.add(1, "test"); } 

and if need more sophisticated behavior, can still stub method calls since methods virtual.


Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -