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:
- public interface IFoo : IDisposable
- void Do();
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 :
- var foo = Mock.Create<IFoo>();
Then, as we are interested only in IDisposable calls, we just need to do the following:
- 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.
- bool called = false;
- Mock.Arrange(() => iDisposable.Dispose()).DoInstead(() => called = true);
Further, we assert our expectation as follows:
- Mock.Assert(() => iDisposable.Dispose(), Occurs.Once());
Hopefully that will help a bit and stay tuned.