只是想要一些指导如何进行单元测试以下操作:
public ActionResult Index()
{
var model = _resolver.GetService<ISignUpViewModel>();
model.Location = _resolver.GetService<ILocations>().getLocations(string area);
return PartialView("Login", model);
}
private IDependencyResolver _resolverMock;
[TestMethod]
public void SignUpTest()
{
var _resolverMock = new Mock<IDependencyResolver>();
var ctrl = new HomeController(_resolverMock.Object);
var signUpMock = new Mock<ISignUpViewModel>();
var LocationsMock = new Mock<ILocations>();
_resolverMock.Setup(m => m.GetService(It.IsAny<Type>())).Returns(
signUpMock.Object);
_resolverMock.Setup(m => m.GetService(It.IsAny<Type>())).Returns(
LocationsMock.Object);
DependencyResolver.SetResolver(resolverMock.Object);
ctrl.Index();
ctrl.ViewData.Model = signUpMock;
}
如何在单元测试中建立模型?
另外如何从解析器中调用getLocations方法?
不确定如何做到这一点?
答案 0 :(得分:0)
根据您的代码,您的家庭控制器不依赖于IDependencyResolver
。它实际上取决于ISignUpViewModel
。因此,您可以将其中一个传递给构造函数或ISignUpViewModelFactory
。所以我会将模型分辨率重构为工厂类:
public class HomeController {
private readonly ISignUpViewModelFactory _modelFactory;
public HomeController(ISignUpViewModelFactory modelFactory){
_modelFactory = modelFactory;
}
public ActionResult Index()
{
return PartialView("Login", _modelFactory.Create(area));
}
}
public interface ISignUpViewModelFactory {
ISignUpViewModel Create(string area);
}
public class ProductionSignUpViewModelFactory : ISignUpViewModelFactory
{
public ISignUpViewModel Create(string area){
// create and return your models here
// if you still have to use a service locator in this factory then
// refactor some more until you get these dependencies out in the open.
}
}
public class MockSignUpViewModelFactory : ISignUpViewModelFactory
{
public ISignUpViewModel Create(string area){
return new SignUpViewModel();
}
}
在制作中,您IOC
会注入ProductionSignUpViewModelFactory
的实例。在测试中,您传入MockSignUpViewModelFactory
。
不同之处在于使用此方法只测试操作(即单元),而使用当前方法测试操作和服务器_resolver
加上你已经模糊了实际的依赖关系ISignUpViewModel
1}}不是IDependencyResolver
。
根据ProductionSignUpViewModelFactory
中的评论,如果您必须向该工厂注入IDependencyResolver
以使其正常工作,那么您可能仍然做错了。然后,您需要查看ProductionSignUpViewModelFactory
创建ISignUpViewModel
实例所需的内容,并注入IDependencyResolver
。
最终,您将进入依赖关系链的顶端,您会发现单元测试变得非常非常简单。如果你首先构建测试,即TDD,则更容易。 :)