Working with multiple interfaces on a single mock.

Posted by mehfuzh on ASP.net Weblogs See other posts from ASP.net Weblogs or by mehfuzh
Published on Mon, 26 Apr 2010 15:35:29 GMT Indexed on 2010/04/26 15:43 UTC
Read the original article Hit count: 295

Filed under:
|
|
|

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. }

Now, as we can see that our target interface has implemented IDisposable and in normal cases if we have to implement it in class where language rules require use to implement that as well[no doubt about it] and whether or not there can be more complex cases, we want to ensure that rather having an extra call(..As()) or constructs to prepare it for us, we should do it in the simplest way possible.

Therefore, keeping that in mind, first we create a mock of IFoo

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

Then, as we are interested with IDisposable, we simply do:

  1. var iDisposable = foo as IDisposable;

 

Finally, we proceed with our existing mock code. Considering the current context, we 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!!

© ASP.net Weblogs or respective owner

Related posts about c#

Related posts about telerik