Working with multiple interfaces on a single mock.
- by mehfuzh
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(); } 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 var foo = Mock.Create<IFooDispose>(); Then, as we are interested with IDisposable, we simply do: 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. bool called = false; Mock.Arrange(() => iDisposable.Dispose()).DoInstead(() => called = true); iDisposable.Dispose(); Assert.True(called); Further, we assert our expectation as follows: Mock.Assert(() => iDisposable.Dispose(), Occurs.Once()); Hopefully that will help a bit and stay tuned. Enjoy!!