Fake a member without passing the instance via 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:
- public class LegacyCode
- {
- public int CheckUser(string userName, string password)
- {
- var _service = new LoginService();
- return _service.ValidateUser(userName, password);
- }
- }
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.
- public class LoginService
- {
- public int ValidateUser(string userName, string password)
- {
- throw new NotImplementedException("Nothing implemented yet.");
- }
- }
Here is the specification that I wrote with Justmock and MSpec
- [Subject(typeof(LoginService))]
- public class when_a_mock_is_called_without_instance_being_injected
- {
- Establish context = () =>
- {
- service = new LoginService();
- Mock.Arrange(() => service.ValidateUser(userName, password)).MustBeCalled();
- };
- private Because of = () =>
- {
- var sut = new LegacyCode();
- sut.CheckUser(userName, password);
- };
- private It must_assert_that_fake_setup_is_invoked_from_context = () =>
- Mock.Assert(service);
- static LoginService service;
- readonly static string userName = "User";
- readonly static string password = "Pwd";
- }
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.