我使用Unity创建CustomerService
的实例。这适用于ASP.NET MVC应用程序中的以下代码。
当我创建ASP.NET MVC应用程序时,我创建了ASP.NET MVC测试项目。我想测试一下这些动作(这里:/Home/Index
)。
问题是我无法设置Unity
。我想创建一个真正的动作调用,而不是嘲笑。
您是否了解测试项目中的设置?我试过这个,但是当我调用控制器时,我找不到正确的语法来创建CustomerService
的实例作为参数。
[TestMethod]
public void Index()
{
var container = UnityConfig.GetConfiguredContainer();
//I don't find the right syntax for resolve
ICustomerService customerService = container.Resolve??????
HomeController controller = new HomeController(customerService);
ViewResult result = controller.Index() as ViewResult;
Assert.IsNotNull(result);
container.Dispose();
}
ASP.NET MVC应用程序中使用的工作代码
namespace MyTestMVC
{
public class HomeController : Controller
{
private readonly ICustomerService _customerService;
public HomeController(ICustomerService customerService)
{
_customerService = customerService;
}
public ActionResult Index()
{
var result = _customerService.MyMethod();
//.....
return View();
}
}
}
//I set Unity like this :
namespace MyTestMVC.App_Start
{
public class UnityConfig
{
private static Lazy<IUnityContainer> container = new Lazy<IUnityContainer>(() =>
{
var container = new UnityContainer();
RegisterTypes(container);
return container;
});
public static IUnityContainer GetConfiguredContainer()
{
return container.Value;
}
public static void RegisterTypes(IUnityContainer container)
{
container.RegisterType<ICustomerService, CustomerService>();
}
}
}
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(MyTestMVC.App_Start.UnityWebActivator), "Start")]
[assembly: WebActivatorEx.ApplicationShutdownMethod(typeof(MyTestMVC.App_Start.UnityWebActivator), "Shutdown")]
namespace MyTestMVC.App_Start
{
public static class UnityWebActivator
{
/// <summary>Integrates Unity when the application starts.</summary>
public static void Start()
{
var container = UnityConfig.GetConfiguredContainer();
FilterProviders.Providers.Remove(FilterProviders.Providers.OfType<FilterAttributeFilterProvider>().First());
FilterProviders.Providers.Add(new UnityFilterAttributeFilterProvider(container));
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
}
public static void Shutdown()
{
var container = UnityConfig.GetConfiguredContainer();
container.Dispose();
}
}
}
答案 0 :(得分:0)
container.Resolve<ICustomerService>();
答案 1 :(得分:0)
&#34;如何在不启动浏览器的情况下测试操作?&#34;
将Moq安装到您的Unit测试项目中。
install-package Moq
然后在您的测试中创建一个ICustomerService的moq实例并存根使用的方法
var mock = new Mock<ICustomerService>();
mock.Setup(x => x.MyMethod()).Returns(true);
然后将模拟对象传递给控制器的实例,然后在控制器上调用该方法
var controller = new HomeController(mock);
var result = controller.MyMethod();
使用Moq,您可以断言是否已调用方法等