Future mocking with #IgnoreInstance

In my previous post, i showed how JustMock picks mock expectations based on current context without the instance being injected. Based on feedback we found that It’s sometimes confusing and often does not work as intended. However, the context of this post is not to introduce future mocking rather a new feature that allows you to skip mock instance intentionally (when you can’t pass the dependency through a constructor or via method argument) instead the tool is applying it for you on behalf.

You can find more on future mocking and some abstract behind it from my previous post:

http://weblogs.asp.net/mehfuzh/archive/2011/09/30/future-mocking-revisited.aspx

Now moving forward, i will represent a code block that fails and then solve it with IgnoreInstance  modifier. I am of course thankful to Lior Friedman for pointing me this. So the code that is very much similar to what he showed me:

Code that fails

  1. var fakeUsed = Mock.Create<UsedClass>();
  2.  
  3. Mock.Arrange(() => fakeUsed.ReturnFive()).Returns(7);
  4.  
  5. Assert.AreEqual(7, fakeUsed.ReturnFive());    
  6.  
  7. Assert.AreEqual(5, new UsedClass().ReturnFive());

Now , if the context resolve is implicit then both of the calls will return the same value. In this typical use case the search by context wont work because for some arrange I might want to ignore instance and for some other I want to execute the call as it is.  Taking this into account, introduced more explicit ignoreInstance switch. This will not only let you ignore instance per setup for the same type also make it more pragmatic and to the point since now I know what I am doing, not the tool getting on my  way.

Therefore only when you want to apply a particular setup for all instance, you will do it like:

  1. var fakeUsed = Mock.Create<UsedClass>();
  2.  
  3. Mock.Arrange(() => fakeUsed.ReturnFive()).Returns(7).IgnoreInstance();
  4.  
  5. Assert.AreEqual(7, fakeUsed.ReturnFive());    
  6.  
  7. Assert.AreEqual(7, new UsedClass().ReturnFive());

 

This is a new feature and available from Q3 2011 build and removes the implicit context search approach.

 

Hope that helps

 

P.S. We are gathering next cool feature for JustMock. Since we believe it’s a tool worth when there is a personal touch therefore please send me / us your ideas in the forum or via email or just a tweet.

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>