Pradeep Gupta
Pradeep Gupta

Reputation: 235

Mocking ASPNET MVC DependencyResolver with Rhino mock

While writing a unit test for one of the business logic(method), not able to mock ASP NET MVC DependencyResolver due to that getting null for this. Below is the line of code

DependencyResolver.Current.GetService(typeof(ITestDetails)) as ITestDetails;

Somehow wanted to mock this line.

Upvotes: 2

Views: 1315

Answers (1)

Nkosi
Nkosi

Reputation: 247591

Mock the resolver and its expected behavior

//create the new resolver that will be used to replace the current one
IDependencyResolver resolver = MockRepository.GenerateMock<IDependencyResolver>();
//mock expected behavior
var testdetails = MockRepository.GenerateMock<ITestDetails>();
resolver.Stub(_ => _.GetService(typeof(ITestDetails))).Returns(testDetails);

and set current to the mock.

//assign the mocked resolver.
DependencyResolver.SetResolver(resolver);

So now when

DependencyResolver.Current.GetService(typeof(ITestDetails))

is invoked, it will provide the mocked resolver and behave as expected when unit testing

Upvotes: 2

Related Questions