Why is this Autofac mock's lifetime disposed in a simple MSpec test? -
i've got base class i'm using mspec provides convenience methods around automock:
public abstract class subjectbuildercontext { static automock _container; protected static isubjectbuilderconfigurationcontext<t> buildsubject<t>() { _container = automock.getloose(); return new subjectbuilderconfigurationcontext<t>(_container); } protected static mock<tdouble> getmock<tdouble>() tdouble : class { return _container.mock<tdouble>(); } }
occasionally, i'm seeing exception happen when attempting retrieve mock so:
it should_store_the_receipt = () => getmock<ifileservice>().verify(f => f.savefileasync(moq.it.isany<byte[]>(), moq.it.isany<string>()), times.once());
here's exception:
system.objectdisposedexceptioninstances cannot resolved , nested lifetimes cannot created lifetimescope has been disposed.
i'm guessing has way mspec runs tests (via reflection) , there's period of time when nothing actively has references of objects in underlying lifetime scope being used automock causes lifetimescope disposed. what's going on here, , there simple way me keep happening?
the automock
lifetime scope autofac.extras.moq
disposed when mock disposed. if you're getting this, means automock
instance has been disposed or has otherwise lost scope , gc has cleaned up.
given that, there few possibilities.
the first possibility you've got potential threading challenges around async method calls. looking @ method that's being mocked, see you're verifying call savefileasync
method. however, don't see async related code in there, , i'm not entirely sure when/how tests running calling given posted code, if there situation async call causes test run on 1 thread while automock
loses scope or otherwise gets killed on other thread, see happening.
the second possibility the mix of static , instance items in context. storing automock
static, appears context class in resides base class intended supply instance-related values. if 2 tests run in parallel, example, first test set automock
thinks needs, second test overwrite automock
, first go out of scope, disposing scope.
the third possibility multiple calls buildsubject<t>
in 1 test. call buildsubject<t>
initializes automock
. if call multiple times in 1 test, despite changing t
type, you'll stomping automock
each time , associated lifetime scope disposed.
the fourth possibility a test ordering problem. if see not other times, tests inadvertently assume setup, call buildsubject<t>
, has been done; while other tests may not make assumption , call buildsubject<t>
themselves. depending on order tests run, may lucky , not see exception, other times may run problem buildsubject<t>
gets called @ wrong time , causes pain.
Comments
Post a Comment