正如标题所说,我正在尝试解析一个实现了一个具体类的接口,该类也接受一个构造函数。
下面以具体的服务类为例:
public class MessageService : IMessageService
{
private readonly IMessageGenerator _messageGenerator;
public MessageService(IMessageGenerator messageGenerator)
{
_messageGenerator = messageGenerator;
}
public string GetMessage()
{
return string.Concat(_messageGenerator.GetMessage(), "");
}
}
如您所见,此服务类还需要一个接口作为构造函数参数。MVC 控制器构造函数如下所示:
private readonly IMessageService _messageSvc;
public HomeController(IMessageService messageSvc)
{
_messageSvc = messageSvc;
}
感谢 Unity.Mvc3,我已经解决了 Bootstrapper 中的接口
var container = new UnityContainer();
container
.RegisterType<IMessageService, MessageService>()
.RegisterType<IMessageGenerator, MessageGenerator>();
所以我遇到的主要问题是如何使用 UnityAutoMoq 在单元测试中将 IMessageGenerator 接口的模拟实例传递给 IMessageService?我认为这样的事情会起作用,但它不会:
[TestMethod]
public void Index()
{
var container = new UnityAutoMoqContainer();
var controllerContext = container.Resolve<ControllerContext>();
var nMsgSvc = container.Resolve<IMessageService>(container.Resolve<IMessageGenerator>);
var sut = new HomeController(nMsgSvc) { ControllerContext = controllerContext };
ViewResult result = sut.Index() as ViewResult;
Assert.AreEqual("Hello from the MessageGenerator via the MessageService", result.ViewBag.Message);
}