c# - exception when mocking a unity container -
i trying mock unity container - using moq , getting errror
system.argumentexception: invalid setup on non-overridable member: c => c.resolve<ilogisticsadapter>(new [] {})
here code setup portion of test.
var mockcontainer = new mock<iunitycontainer>(); mockcontainer.setup(c => c.resolve<ilogisticsadapter>()).returns(logicsticsadapter); iunitycontainer container = mockcontainer.object;
what missing? no master @ mocks in general or unit testing can tell should work...
just in case important using vs2010 , ms test...
thanks
here whole test fixture -you can see have changed use real unity container ideally don't want create real unity container - isn't testing. can see code commented out...
[testmethod] public void whencontructed_adaptergetsset() { //prepare ilogisticsadapter logicsticsadapter = new mock<ilogisticsadapter>().object; var mockeventaggregator = new mock<ieventaggregator>(); mockeventaggregator.setup(x => x.getevent<sethelpmessageevent>()).returns(new sethelpmessageevent()); ieventaggregator eventaggregator = mockeventaggregator.object; iregionmanager regionmanager = new mock<iregionmanager>().object; //var mockcontainer = new mock<iunitycontainer>(); //mockcontainer.setup(c => c.resolve<ilogisticsadapter>(null)).returns(logicsticsadapter); //iunitycontainer container = mockcontainer.object; iunitycontainer container = new unitycontainer(); container.registerinstance<ilogisticsadapter>(logicsticsadapter); container.registerinstance<iregionmanager>(regionmanager); container.registerinstance<ieventaggregator>(eventaggregator); //act var warehouseordersviewmodel = new warehouseordersviewmodel_accessor(container); assert.isnotnull(warehouseordersviewmodel.logisticsadapter); }
thanks!
i agree above commenters - shouldn't (in cases) referencing container anywhere other bootstrapper. in case, looks you're implementing view model locator type of class, might ok. however, please think whether right thing do. using explicit factories or getting func injected container same place without coupling explicitly container.
having said that, if you're using unity 2.0, take @ iunitycontainer interface. you'll see method you're trying mock out isn't on interface. it's extension method. iunitycontainer has 1 "native" resolve method:
object resolve(type t, string name, params resolveroverride[] resolveroverrides);
so you'll need mock that method specifically. extension methods parameter juggling , turn around , call resolve that's directly on interface.
you might still run issues - there's bug in .net framework causes problems when codegenning implementations of interfaces have methods return interface well, registertype, registerinstance, and, every other method on iunitycontainer does. problem mocking frameworks know of right now. if do hit this, option manual mock - write class implements iunitycontainer rather using mock framework it.
Comments
Post a Comment