开发者

testing controller using MOQ calling repository

开发者 https://www.devze.com 2023-01-22 05:38 出处:网络
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.

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 co开发者_运维百科ntroller = 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);
    }

}


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

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

0

精彩评论

暂无评论...
验证码 换一张
取 消