Fake a member without worrying about passing the dependency

I have came across this several times in forum (telerik) on how I can really fake an item yet I don’t want to pass the instance as an argument. Ideally, this is not a best design but there are third- partly libraries that you have little control over how its written.  Anyway, whatever the case might be. This post will show you how you can achieve the above using JustMock. I will be using MSpec in conjunction for the example.

 

So here is the sample class that I am going to use:

 

  1. public class LegacyCode
  2. {
  3.     public int CheckUser(string userName, string password)
  4.     {
  5.         var _service = new LoginService();
  6.         return _service.ValidateUser(userName, password);
  7.     }
  8. }

Here CheckUser is calling  LoginService.ValidateUser that we are going replace with a fake call. Also here is the  LoginService class that is not much significant just throws exception when ValidateUser is called that will even confirm if the correct variant is invoked.

 

  1. public class LoginService
  2. {
  3.     public int ValidateUser(string userName, string password)
  4.     {
  5.         throw new NotImplementedException("Nothing here");
  6.     }
  7. }

 

Here is the specification that I wrote with Justmock and MSpec

 

  1. [Subject(typeof(LoginService))]
  2.   public class when_a_mock_is_called_without_instance_being_injected
  3.   {
  4.       Establish context = () =>
  5.       {
  6.           service = new LoginService();
  7.           Mock.Arrange(() => service.ValidateUser(userName, password)).MustBeCalled();
  8.       };
  9.  
  10.       private Because of = () =>
  11.       {
  12.           var sut = new LegacyCode();
  13.           sut.CheckUser(userName, password);
  14.       };
  15.  
  16.       private It must_assert_that_fake_setup_is_invoked_from_context = () =>
  17.           Mock.Assert(service);
  18.  
  19.  
  20.       static LoginService service;
  21.       readonly static string userName = "User";
  22.       readonly static string password = "Pwd";
  23.   }

 

This concludes that if you have a mock setup and you cant pass the instance via dependency injection, JustMock will still try to find the closest mock setup for arguments that it will replace the original call with when invoked. There is no extra setup call to be associated in that regard and keeps the tool more out of your way.

 

In addition I am attaching the sample project to let you have a look. Also you will be needing JustMock full edition installed to try this out.

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>