Question

I need some help setting up an NUnit test for a ASP.net MVC 4 application using Unity Container.

I am using a bootstrapper class file to create the Unity Container.

Bootstrapper class:

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;
    }

Controller:

public class CustomerController : Controller
    {

        readonly ICustomerRepository repository;

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

        public ViewResultIndex()
        {

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

    }

NUnit Test Project :

[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);
        }

    }

I am uncertain how to pass in the ICustomerRepository to the CustomerController constructor in the NUnit test project.

Thanks in advance!!

Was it helpful?

Solution

You don't need to use the container in the unit test, the point of the unit test is isolated testing of the "system under test (SUT)" which in this case is your CustomerController class.

What you should be doing is creating a mock implementation of your ICustomerRepository which you supply to the constructor of the CustomerController something like this:

[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());
}

This is based upon the Moq framework and a fictional use case based upon your example but should give you an idea to get you going.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top