MVC 4 Unity容器和NUnit测试

时间:2014-01-02 19:25:15

标签: asp.net-mvc-4 nunit ioc-container

我需要一些帮助,使用Unity Container为ASP.net MVC 4应用程序设置NUnit测试。

我使用bootstrapper类文件来创建Unity容器。

Bootstrapper类:

public static class Bootstrapper
  {
    public static IUnityContainer Initialise()
    {
      var container = BuildUnityContainer();

      DependencyResolver.SetResolver(new UnityDependencyResolver(container));

      return container;
    }

 private static IUnityContainer BuildUnityContainer()
    {
      // Create a new Unity dependency injection container
      var container = new UnityContainer();

      // register all your components with the container here                
      container.RegisterType<ICustomerRepository, CustomerRepository>();
      RegisterTypes(container);

      return container;
    }

控制器:

public class CustomerController : Controller
    {

        readonly ICustomerRepository repository;

        public CustomerController (ICustomerRepository repository)
        {
            this.repository = repository;
        }

        public ViewResultIndex()
        {

            var data = repository.GetAll();
            return View(data);
        }

    }

NUnit测试项目:

[TestFixture]
    class CustomerUnitTests
    {


        [Test]
        public void Customer_Index_Returns_ViewResult()
        {
            //Arrange 
            CustomerController controller = new CustomerController();

            //ACT 
            var actual = controller.Index();

            //Assert 
            Assert.IsInstanceOf<ViewResult>(actual);
        }

    }

我不确定如何将ICustomerRepository传递给NUnit测试项目中的CustomerController构造函数。

提前致谢!!

1 个答案:

答案 0 :(得分:1)

您不需要在单元测试中使用容器,单元测试的要点是“被测系统(SUT)”的隔离测试,在这种情况下是您的CustomerController类。 / p>

您应该做的是创建ICustomerRepository的模拟实现,并将其提供给CustomerController的构造函数,如下所示:

[Test]
public void Customer_Index_Returns_ViewResult()
{
    var customers = new [] { new Customer(), new Customer() };

    var mockRepository = new Mock<ICustomerRepository>();
    mockRepository.Setup(r => r.GetLatestCustomers()).Returns(customers);

    //Arrange 
    CustomerController controller = new CustomerController(mockRepository.Object);

    //ACT 
    var actual = controller.Index();

    //Assert 
    Assert.IsInstanceOf<ViewResult>(actual);

    mockRepository.Verify(r => r.GetLatestCustomers(), Times.Once());
}

这是基于Moq框架和基于您的示例的虚构用例,但应该给您一个让您前进的想法。