我对Mocking很新。在下面的例子中,我正在使用Moq并尝试创建一个_companyRepository。但是第二个测试有一个空参考。即公司未实例化。
Assert.AreEqual(viewModel.Company.Name, "MyCompany");
想想我在这里错过了一些愚蠢的东西。
[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");
}
}
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);
}
}
答案 0 :(得分:0)
这是有效的....猜猜我没有编译所有东西。非常愚蠢。
我正在以正确的方式做这件事。感谢任何评论。