Telerik blogs

Today , I will cover a very simple topic, which can be useful in cases we want to mock different interfaces on our expected mock object.  Our target interface is simple and it looks like:

  1.  
  2. public interface IFoo : IDisposable
  3. {
  4.     void Do();
  5. }

Our target interface has an IDisposable implemented. Now, generally if we implement it in a class , we have to implement the whole of it [which is quite logical] and that should not wait for any extra calls or constructs. Considering that, when we are creating our target mock it should also implement all the dependent interfaces for us as well.  

Therefore,  as we are creating our mock using Mock.Create<IFoo> like that follows, it also implements the dependencies for us :

  1. var foo = Mock.Create<IFoo>();

Then,  as we are interested only in IDisposable calls, we just need to do the following:

  1. var iDisposable = foo as IDisposable;

Finally, we proceed with our existing mock code. Considering the current context, I will check if the dispose method has invoked our mock code successfully.

 

  1. bool called = false;
  2.  
  3. Mock.Arrange(() => iDisposable.Dispose()).DoInstead(() => called = true);
  4.  
  5.  
  6. iDisposable.Dispose();
  7.  
  8. Assert.True(called);

 

Further, we assert our expectation as follows:

  1. Mock.Assert(() => iDisposable.Dispose(), Occurs.Once());

 

Hopefully that will help a bit and stay tuned.

Enjoy!!


Comments

Comments are disabled in preview mode.