MVC 3: How to learn how to test with NUnit, Ninject, and Moq?

前端 未结 3 675
悲&欢浪女
悲&欢浪女 2021-01-29 20:04

Short version of my questions:

  1. Can anyone point me toward some good, detailed sources from which I can learn how to implement testing in my MVC 3
3条回答
  •  清酒与你
    2021-01-29 20:52

    1. Here is the application that I'm creating. It is open source and available on github, and utilizes all of the required stuff - MVC3, NUnit, Moq, Ninject - https://github.com/alexanderbeletsky/trackyt.net/tree/master/src

    2. Contoller-Repository decoupling is simple. All data operations are moved toward the Repository. Repository is an implementation of some IRepository type. The controller never creates repositories inside itself (with the new operator) but rather receives them either by constructor argument or property.

    .

    public class HomeController {
      public HomeController (IUserRepository users) {
    
      }
    }
    

    This technique is called "Inversion of Control." To support inversion of control you have to provide some "Dependency Injection" framework. Ninject is a good one. Inside Ninject you associate some particular interface with an implementation class:

    Bind().To();
    

    You also substitute the default controller factory with your custom one. Inside the custom one you delegate the call to the Ninject kernel:

    public class TrackyControllerFactory : DefaultControllerFactory
    {
        private IKernel _kernel = new StandardKernel(new TrackyServices());
    
        protected override IController GetControllerInstance(
            System.Web.Routing.RequestContext requestContext,
            Type controllerType)
        {
            if (controllerType == null)
            {
                return null;
            }
    
            return _kernel.Get(controllerType) as IController;
        }
    }
    

    When the MVC infrastructure is about to create a new controller, the call is delegated to the custom controller factory GetControllerInstance method, which delegates it to Ninject. Ninject sees that to create that controller the constructor has one argument of type IUserRepository. By using the declared binding, it sees that "I need to create a UserRepository to satisfy the IUserRepository need." It creates the instance and passes it to the constructor.

    The constructor is never aware of what exact instance would be passed inside. It all depends on the binding you provide for that.

    Code examples:

    • https://github.com/alexanderbeletsky/trackyt.net/blob/master/src/Web/Infrastructure/TrackyServices.cs https://github.com/alexanderbeletsky/trackyt.net/blob/master/src/Web/Infrastructure/TrackyControllerFactory.cs https://github.com/alexanderbeletsky/trackyt.net/blob/master/src/Web/Controllers/LoginController.cs

提交回复
热议问题