how to unit test asp.net core application with constructor dependency injection

后端 未结 5 1316
难免孤独
难免孤独 2020-12-07 10:43

I have a asp.net core application that uses dependency injection defined in the startup.cs class of the application:

    public void ConfigureServices(ISer         


        
5条回答
  •  心在旅途
    2020-12-07 11:02

    Your controllers in .net core have dependency injection in mind from the start, but this does not mean you are required to use a dependency injection container.

    Given a simpler class like:

    public class MyController : Controller
    {
    
        private readonly IMyInterface _myInterface;
    
        public MyController(IMyInterface myInterface)
        {
            _myInterface = myInterface;
        }
    
        public JsonResult Get()
        {
            return Json(_myInterface.Get());
        }
    }
    
    public interface IMyInterface
    {
        IEnumerable Get();
    }
    
    public class MyClass : IMyInterface
    {
        public IEnumerable Get()
        {
            // implementation
        }
    }
    

    So in your app, you're using the dependency injection container in your startup.cs, which does nothing more than provide a concretion of MyClass to use when IMyInterface is encountered. This does not mean it is the only way of getting instances of MyController however.

    In a unit testing scenario, you can (and should) provide your own implementation (or mock/stub/fake) of IMyInterface as so:

    public class MyTestClass : IMyInterface
    {
        public IEnumerable Get()
        {
            List list = new List();
            // populate list
            return list;
        }        
    }
    

    and in your test:

    [TestClass]
    public class MyControllerTests
    {
    
        MyController _systemUnderTest;
        IMyInterface _myInterface;
    
        [TestInitialize]
        public void Setup()
        {
            _myInterface = new MyTestClass();
            _systemUnderTest = new MyController(_myInterface);
        }
    
    }
    

    So for the scope of unit testing MyController, the actual implementation of IMyInterface does not matter (and should not matter), only the interface itself matters. We have provided a "fake" implementation of IMyInterface through MyTestClass, but you could also do this with a mock like through Moq or RhinoMocks.

    Bottom line, you do not actually need the dependency injection container to accomplish your tests, only a separate, controllable, implementation/mock/stub/fake of your tested classes dependencies.

提交回复
热议问题