c# - Change injection in Autofac module with a mock (Moq) object -


i have autofac module below

    public class serviceinjector:module     {         protected override void load(containerbuilder builder)             {                 // many registrations , type looking here                 ...                 // 1 of registration, t found                 // in above looking, resource consuming type                  builder.registertype(t).as<itimeconsume>();                  // ...             }     } 

and module used in serviceclass:

public class serviceclass {     static icontainer _ioc;     public serviceclass()     {         var builder = new containerbuilder();         builder.registermodule<serviceinjector>();          _ioc = builder.build();          }      public void invokeservice()     {         using(var scope = _ioc.beginlifetimescope())         {             itimeconsume obj = scope.resolve<itimeconsume>(...);              var result = obj.dotimeconsumingjob(...);              // result here ...         }         } } 

my questions is: how test serviceclass mocking (moq) itimeconsume class ? here try write test below:

public void test() {     mock<itimeconsume> moc = getmockobj(...);      // how can inject moc.object serviceinjector module,     // serviceclass can use mock object ? } 

if not possible way, what's better design mocking time consuming class can injected?

**

update:

** @dubs , @oldfox hints. think key autofac injector should initialized externally instead of internal controlled. leverage 'on fly' building capability of autofac.ilifetimescope , design serviceclass constructor lifetime scope parameter. design can on-flying registering service in unit test below example:

using(var scope = ioc.beginlifetimescope(     builder =>  builder.registerinstance(mockobject).as<itimeconsume>()) 

in current design cannot inject mock object. simplest solution least changes add internal cto'r serviceclass:

internal serviceclass(icontainer ioc) {     _ioc = ioc;      } 

then use attributte internalsvisibleto enable using of c`tor in test class.

in arrange/setup/testinit phase initialize class under test container contains mock object:

    [setup]     public void testinit()     {         mock<itimeconsume> moc = getmockobj(...);         builder.registerinstance(moc).as<itimeconsume>();         ...         ...         _target = new serviceclass(builder.build());     } 

Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -