Padmalochan
Padmalochan

Reputation: 1090

Assert.IsInstanceOfType failed in Moq Package in Mvc3

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

Upvotes: 2

Views: 1291

Answers (1)

nemesv
nemesv

Reputation: 139788

Moq returns null by default for each non void method call.

So when in your controller you call _repository.GetPermitDetails(); it return null that's why your test fails.

You need to call Setup on your method to return something:

var messagingService = new Mock<IPermitRepository>();
messagingService.Setup(m => m.GetPermitDetails()).Returns(new PermitModel());
var controller = new HomeController(messagingService.Object);

You can find more info in the Moq quickstart on how to customize the mock behaviour.

Upvotes: 2

Related Questions