Unit Test C# MOQ dependecy injection

Viewed 1057

I am new to Unit test. Trying to integrate unit test for legacy code. To moq the same method of the class, do i need to inject the interface or is there any other option.??

If interface injection to the constructor is the only way, how to define the default constructor for the existing code. Example:

    private IController _iController;
    public Controller(IController iController)
    {
        _iController= iController;

    } 
    public ActionResult ActualMethod()
    { 
        _iController.FillViewBag(); 
        return View();
    }
    public void UnitTest()
    {
       var i = new Mock<IController>();
        i.Setup(d => d.FillViewBag());
        var controller = new Controller(i.Object); 
        controller.ActualMethod();
    }

For the above code i am able to perform unit test. But if i browse the method(manually test the action) it is failing object ref not set. as the object is empty. How to fix this issue?

Also i am using FillViewBag in many places, those place i dont want to change the call based on interface for now. Please advise.

1 Answers
Related