存储库是Mvc控制器的支柱,我正在尝试编写一个测试方法来检查这个控制器, 但我在集装箱电话中收到错误......
我是mvc和测试中的新手..所以我不知道从哪里开始 我怎么能这样做?
这是测试的样子:
public void SomeTest()
{
var controller= new SomeController();
var result = SomeController.Index();
Assert.IsNotNull(result);
}
我运行测试时出现的错误
SomeContext.dll中出现类型System.NullReferenceException
的例外,但未在用户代码中处理
答案 0 :(得分:0)
您的存储库是否已初始化? 在您的控制器中:
private Repository Repository {get;set;}
public ActionResult Index()
{
Repository = new Repository();
var something = Repository.DoSomeWork();
return View(something);
}
在您的测试课程中:
public void SomeTest()
{
var controller = new SomeController();
var result = controller.Index();
Assert.IsNotNull(result);
}
或者如果您使用依赖注入,使用Ninject属性注入,您可以尝试使用Moq注入类:
public class SomeController : Controller
{
private IRepository repository;
[Inject]
public IRepository Repository
{
get { return repository; }
set { repository = value; }
}
// GET: /Some/
public ActionResult Index()
{
var someCollection = Repository.SomeMethod("some parameter");
foreach (var value in someCollection)
{
ViewData["message"] += value;
}
return View(someCollection);
}
}
和moq的测试类:
public class SomeTestClass
{
private Mock<IRepository> mockRepository;
[Test]
public void GivenSometestThenExpectSomeResult()
{
// Arrange
var controller = new SomeController();
mockRepository = new Mock<IRepository>();
mockRepository.Setup(x => x.SomeMethod(It.IsAny<string>())).Returns(new List<string>());
controller.Repository = mockRepository.Object;
// Act
ActionResult result = controller.Index();
// Assert
Assert.AreEqual("Index", result.ViewName);
}
}