Reputation: 31
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.
Upvotes: 2
Views: 1165
Reputation: 11841
You mock the IController interface and then pass the mocked object into your constructor.
var mockController = new Mock<IController>();
var controller = new Controller(mockController.Object);
You also need to setup what you want the mocked FillViewBag to do:
var mockController.Setup(c => c.FillViewBag).Callback(() => do something here);
Plenty of info for this in the Moq Quickstart
Upvotes: 4