gpt4 book ai didi

c# - ASP.NET MVC、RavenDb 和单元测试

转载 作者:太空狗 更新时间:2023-10-29 22:23:43 25 4
gpt4 key购买 nike

我刚刚开始使用 RavenDB,到目前为止我很喜欢它。然而,我仍然坚持我应该如何对与之交互的 Controller 操作进行单元测试。

我找到的所有问题/文章都是这样的:Unit testing RavenDb queries告诉我我应该在内存中使用 RavenDB 而不是模拟它,但我找不到一个具体的例子来说明如何做到这一点。

例如,我有一个 Controller 操作来将员工添加到数据库中(是的,它过于简化了,但我不想使问题复杂化)

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,但我很乐意尝试翻译来自其他框架的测试。

谢谢。

编辑

好的,我的测试初始化​​创建了注入(inject) Controller 构造函数的文档存储,但是当我运行我的测试时,OnActionExecuting 事件没有运行,所以没有 session 可以使用,并且测试失败并出现空引用异常。

[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.
}
}

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

最佳答案

运行单元测试后,只需断言数据库中有一个新文档并且它设置了正确的字段。

var newDoc = session.Load<T>(docId)

var docs = session.Query<T>.Where(....).ToList();

存在 RavenDB 内存模式,因此您不必模拟它,您只需执行以下操作:

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

更新 如果你想要一个完整的示例,看看 RacoonBlog 代码是如何做到的,这是运行 Ayende's blog 的代码.查看这两个文件:

关于c# - ASP.NET MVC、RavenDb 和单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10421700/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com