0
votes

I have the following class that needs to be tested.

public ReportViewModel
{
    public ReportViewModel()
    {           
        using (var repository = new ExecutionDetailsReportRepository())
        {
           this._reportData= repository.GetExecutionDetailsReport(testManager.ExecutionDetail.ExecutionId);
        }
     }
}

The constructor creates a new ExecutionDetailsReportRepository and this needs to be mocked

My Test method has the mock setup like this

var mockExecutionDetailsReportRepository = new Mock<IExecutionDetailsReportRepository>(MockBehavior.Loose);
mockExecutionDetailsReportRepository.Setup(ed => ed.GetExecutionDetailsReport(null)).Returns((List<ExecutionDetailsReport> x) => x).Verifiable();

GetExecutionDetailsReport takes a int? as parameter type. I tried setting it up with 0 or It.IsAny but still my test ends up createing a new real instance of GetExecutionDetailsReport rather than using the Mocked instance.

Please help me understand what is wrong in my Mock Setup? Im using Moq 4.0

1
Umm... You're not even injecting the interface you want to mock (?). You just create a raw new instance in using block, I'm not quite sure how you want to mock that. - Patryk Ćwiek
Thanks. I have done it this way and it is fine - Sundararajan S

1 Answers

2
votes

As Doc says, you are going to need inject the Repository instance. Dependency Injection is essentially a pre-requisite to Mocking. Read up on ninject or Unity (unity the Dependency Injector, not the game engine).

The most common pattern for this is "Constructor Injection" and would involve your constructor looking like

public ReportViewModel(IExecutionDetailsReportRepository xdrp)

You would then use xdrp instead of a New'd up instance. In the test you pass your mock, in your live code you will rely on Unity, Ninject, etc to get an instance in there... as I said, read up on those:

http://www.ninject.org/

http://unity.codeplex.com/