2

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

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.