views:

27

answers:

1

I'm very new to Mocking. In the below example i'm using Moq and trying to create a _companyRepository. However the second test has a null ref. ie Company is not instantiated.

Assert.AreEqual(viewModel.Company.Name, "MyCompany");

Think i'm missing something silly here.

    [TestClass]
    public class ErrorControllerTest
    {

        private Mock<ICompanyRepository> _companyRepository;

        public ErrorController CreateErrorController()
        {
            _companyRepository = new Mock<ICompanyRepository>();
            _companyRepository.Setup(c => c.Get(2)).Returns(new Company {Name = "MyCompany"});
            return new ErrorController(_companyRepository.Object);
        }


        [TestMethod]
        public void Test()
        {

            var controller = CreateErrorController();
            controller.Test(""); // action is called
            var viewModel = (ErrorViewModel)controller.ViewData.Model;
            Assert.IsInstanceOfType(controller.ViewData.Model, typeof(ErrorViewModel));
            Assert.AreEqual(viewModel.Company.Name, "MyCompany");
        }
     }

controller

public class ErrorController : Controller
{

   private readonly ICompanyRepository _companyRepository;

    public ErrorController(ICompanyRepository companyRepository) 
    {
        _companyRepository = companyRepository;
    }


    public ActionResult Test()
    {
        var company = _companyRepository.Get(2);
        var viewModel = new ErrorViewModel
        {
            Company = company
        };

        return View(viewModel);
    }

}
A: 

this works.... Guess i didn't compile everything. Very dumb.

Tho am i doing this the right way. Appreciate any comments.

frosty