c# - RhinoMock - Use a real object, but stub a single method -
i'm writing unit test against mvc controller has dependency on ifoo. foo (the implementation) has 1 method i'd stub, want leave other intact. how can set using rhinomock?
foo has several dependencies i'd prefer not mock save writing additional lines of code , cluttering test.
foo :
public interface ifoo{ int method1(); int method2(); } public class foo : ifoo{ //lot's of dependencies public foo(ibar bar, ibaz baz, istackoverflow so){} } test:
[test] public void what_i_have_so_far(){ //arrange //load real ifoo ninject (di) var mockfoo = new ninject.kernel(new myexamplemodule()) .get<ifoo>(); //i want test use real method1, not method2 //so stub method2 mockfoo .stub(x => x.method2()) //<---- blows here .returns(42); //act var controllerundertest = new controller(mockfoo); error:
using approach, rhinomock throws exception:
system.invalidoperationexception : object 'myapplication.myexamplemodule' not mocked object.
question:
how can stub method2?
i know create ifoo mock via mockrepository.generatemock, then'd i'd have copy real implementation of method1.
update:
both brad , jimmy's solution seam work equally well, picked brad's because less code write.
however, after researching bit further, looks need automocker. there seams 1 structuremap , moq, not rhinomocks: https://github.com/rhinomocks/rhinomocks/issues/3
you have other way around. create mocked ifoo , redirect some calls real ifoo (this has done via whencalled extension):
var realfoo = new ninject.kernel(new myexamplemodule()).get<ifoo>(); var mockfoo = mockrepository.generatestub<ifoo>(); mockfoo.stub(f => f.method2()).return(42); mockfoo.stub(f => f.method1()) .whencalled(invocation => { invocation.returnvalue = realfoo.method2(); }) .return(whatevervalue); the final return required though override few lines before. otherwise rhino throw exception.
Comments
Post a Comment