Working with multiple interfaces on a single mock.

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 dependant 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!!

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>