I am Using Moq package for testing a Controller.
HomeController.cs
public class HomeController : Controller
{ readonly IPermitRepository _repository;
public HomeController(IPermitRepository rep)
{ this._repository = rep; }
public ViewResult Index()
{
ViewBag.Message = "Hello World";
PermitModel model = _repository.GetPermitDetails();
return View(model);
}
}
In HomeControllerTest.cs
[TestClass]
Public class HomeControllerTest
{
[TestMethod]
public void Index()
{
var messagingService = new Mock<IPermitRepository>();
var controller = new HomeController(messagingService.Object);
var result = controller.Index() as ViewResult;
Assert.IsInstanceOfType(result.Model, typeof(PermitModel));
}
}
But its giving error.
Assert.IsInstanceOfType failed. Expected type:. Actual type:<(null)>.
Can some one provide solution and also some inf about Moq package in MVC3.
Thanks in advance
Moq returns
nullby default for each non void method call.So when in your controller you call
_repository.GetPermitDetails();it returnnullthat’s why your test fails.You need to call
Setupon your method to return something:You can find more info in the Moq quickstart on how to customize the mock behaviour.