Telerik blogs

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 implemented yet.");
  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.       private Because of = () =>
  10.       {
  11.           var sut = new LegacyCode();
  12.           sut.CheckUser(userName, password);
  13.       };
  14.       private It must_assert_that_fake_setup_is_invoked_from_context = () =>
  15.           Mock.Assert(service);
  16.       static LoginService service;
  17.       readonly static string userName = "User";
  18.       readonly static string password = "Pwd";
  19.   }

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.


Comments

Comments are disabled in preview mode.