我剛剛開始使用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.
}
}
我錯過了什麼?我如何獲得在測試中創建的會話?
我已經更新了我的問題,請參見下面 –