ASP.NET MVC,RavenDb和单元测试

Nic*_*ick 5 c# asp.net-mvc unit-testing mstest ravendb

我刚刚开始使用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");
  }
Run Code Online (Sandbox Code Playgroud)

如何在单元测试中验证添加到数据库的内容?有没有人在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.
  }
}
Run Code Online (Sandbox Code Playgroud)

我错过了什么?如何创建在测试中使用的会话?

Mat*_*ren 7

运行单元测试后,只需声明数据库中有新文档,并且设置了正确的字段.

var newDoc = session.Load<T>(docId)
Run Code Online (Sandbox Code Playgroud)

要么

var docs = session.Query<T>.Where(....).ToList();
Run Code Online (Sandbox Code Playgroud)

RavenDB内存模式是存在的,所以你不必嘲笑它,你只需要执行以下操作:

  • 打开一个新的内存嵌入式doc存储(没有数据)
  • 如果需要,请插入单元测试需要运行的任何数据
  • 运行单元测试
  • 查看内存存储中的数据,看看它是否已正确更新

更新如果您需要完整示例,请查看RacoonBlog代码如何执行此操作,这是运行Ayende博客的代码.看到这两个文件: