使用 Rhino mock 模拟 ASPNET MVC DependencyResolver

Mocking ASPNET MVC DependencyResolver with Rhino mock

在为其中一个业务逻辑(方法)编写单元测试时,无法模拟 ASP NET MVC DependencyResolver,因为它为此变得空了。下面是代码行

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

不知何故想嘲笑这一行。

模拟解析器及其预期行为

//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);

并将电流设置为模拟。

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

所以现在

DependencyResolver.Current.GetService(typeof(ITestDetails))

被调用,它将提供模拟解析器并在单元测试时按预期运行