我刚刚开始使用RavenDB,并且我喜欢它。然而,我坚持如何单元测试控制器与其交互的操作。ASP.NET MVC,RavenDb和单元测试
我已经找到像这样的所有问题/文章:Unit testing RavenDb queries告诉我我应该在内存中使用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如果重要,但我很乐意尝试翻译来自其他框架的测试。
谢谢。
编辑
好吧,我测试的initialise创建注入的控制器构造文档存储,但是当我运行我的测试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.
}
}
我错过了什么?我如何获得在测试中创建的会话?
我已经更新了我的问题,请参见下面 –