chevron-thin-right chevron-thin-left brand cancel-circle search youtube-icon google-plus-icon linkedin-icon facebook-icon twitter-icon toolbox download check linkedin phone twitter-old google-plus facebook profile-male chat calendar profile-male
0 votes
I have a static class such as this:

public static class CarService
    private static ICarRepository _carRepository = RepositoryFactory.GetInstance().GetRepository(typeof(ICarRepository)) as ICarRepository  
    public static bool MethodA()
        if (MethodB == true)


    public static bool MethodB()
        //Do something

    public static void MethodC()
        //Do something


And mocking code:

Type carRepositoryType = typeof(CarRepository);
RepositoryFactory fakeFactory = Isolate.Fake.Instance<RepositoryFactory>(Members.ReturnRecursiveFakes);
fakeCarRepository = Isolate.Fake.Instance<CarRepository>(Members.ReturnRecursiveFakes);
Isolate.WhenCalled(() => fakeFactory.GetRepository(carRepositoryType )).WillReturn(fakeCarRepository );           
Isolate.Swap.AllInstances<CarRepository>().With(fakeCarRepository );

Isolate.WhenCalled(() => CarService. MethodB().WillReturn(true);            
Isolate.WhenCalled(() => CarService. MethodC().IgnoreCall();
Isolate.WhenCalled(() => mockCarRepository. DoCRUD()). IgnoreCall();

CarService. MethodA();

The issue I'm having is that the above test always fails because the _carRepository referenced in MethodA is always null. Am I setting up my mocks incorrectly? or is there a bug in TypeMock (5.4)?[/code]
asked by JasonW (2.3k points)

2 Answers

0 votes

The problem in the test is that you are swapping fakeCarRepository and use it as a return value from fakeFactory.GetRepository
The swapping is redundant here.
You can do the same with a shorter test like this:
public void Test()
   var fakeCarRepository = Isolate.Fake.Instance<CarRepository>();

   Isolate.WhenCalled(()=> RepositoryFactory.GetInstance().GetRepository(null)).WillReturn(fakeCarRepository);
   Isolate.WhenCalled(()=> CarService.MethodB()).WillReturn(true);
   Isolate.WhenCalled(() => CarService. MethodC()).IgnoreCall();
   CarService. MethodA();

:arrow: In the line:
Isolate.WhenCalled(()=> RepositoryFactory.GetInstance().GetRepository(null)).WillReturn(fakeCarRepository);
I'm faking a whole chain of calls in on line, also I don't need to specify the exact argument type for GetRepository() so I used null instead.

:arrow: Members.ReturnRecursiveFakes is the default behavior for fakes so you don't need to specify it explicitly when you're creating fakes.
This makes the line shorter and readable for future generations :D

Please let me know if solves your problem.
answered by ohad (35.4k points)
0 votes

Your suggestion worked like a charm.


answered by JasonW (2.3k points)