简体   繁体   中英

Mock an object that should do an action in its constructor with MoQ

I've a class that is doing a very specific job: instantiate an object and ensure that the object is disposed on the same thread it has been created(I've some locks that require this behavior, but this is not the subject).

ManagedLifeCycleObjectInstantier<SomeType> myInstance = ManagedLifeCycleObjectInstantier<SomeType>.Instantiate()){
myInstance.InstantiatedObject //Here my instantiated object is available

//Some other thread calls
//Then when the instantier is disposed, it ensure that the instance also get disposed, but on the correct thread.
myInstance.Dispose();

I would like to UnitTest my ManagedLifeCycleObjectInstantier , one of my case is that there is an exception thrown from the constructor of SomeType , I've to make sure that I receive this exception and that the ManagedLifeCycleObjectInstantier doesn't stay stuck on this.

No need for a full mock. Just create a class for testing that throws in it's constructor and

Assert.That(
    () => ManagedLifeCycleObjectInstantiator.Instantier<MyType>(),
    Throws.TypeOf<MyException>());

For the thread test, it's not clear what you want to test. What is supposed to happen if you dispose it on the wrong thread?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM