我刚刚开始使用 RavenDB,到目前为止我很喜欢它。然而,我坚持如何对与之交互的控制器操作进行单元测试。
我发现的所有问题/文章都像这样:单元测试 RavenDb 查询告诉我应该在内存中使用 RavenDB 而不是模拟它,但我找不到一个可靠的例子来说明这是如何完成的。
例如,我有一个控制器操作来将员工添加到数据库(是的,它过于简化了,但我不想让问题复杂化)
public class EmployeesController : Controller
{
IDocumentStore _documentStore;
private IDocumentSession _session;
public EmployeesController(IDocumentStore documentStore)
{
this._documentStore = documentStore;
}
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
_session = _documentStore.OpenSession("StaffDirectory");
}
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
if (_session != null && filterContext.Exception == null) {
_session.SaveChanges();
_session.Dispose();
}
}
[HttpGet]
public ViewResult Create()
{
return View();
}
[HttpPost]
public RedirectToRouteResult Create(Employee emp)
{
ValidateModel(emp);
_session.Store(emp);
return RedirectToAction("Index");
}
如何验证单元测试中添加到数据库的内容?有没有人有任何在 MVC 应用程序中涉及 RavenDb 的单元测试示例?
如果这很重要,我正在使用 MSTest,但我很乐意尝试翻译来自其他框架的测试。
谢谢。
编辑
好的,我的测试初始化创建了注入到控制器构造函数中的文档存储,但是当我运行我的测试时,OnActionExecuting 事件没有运行,因此没有要使用的会话,并且测试失败并出现空引用异常。
[TestClass]
public class EmployeesControllerTests
{
IDocumentStore _store;
[TestInitialize]
public void InitialiseTest()
{
_store = new EmbeddableDocumentStore
{
RunInMemory = true
};
_store.Initialize();
}
[TestMethod]
public void CreateInsertsANewEmployeeIntoTheDocumentStore()
{
Employee newEmp = new Employee() { FirstName = "Test", Surname = "User" };
var target = new EmployeesController(_store);
ControllerUtilities.SetUpControllerContext(target, "testUser", "Test User", null);
RedirectToRouteResult actual = target.Create(newEmp);
Assert.AreEqual("Index", actual.RouteName);
// verify employee was successfully added to the database.
}
}
我错过了什么?如何创建会话以在测试中使用?