0
我正試圖在mvc4中研究實體框架。我使用CRUD操作在EF中創建了一個項目。現在我想單元測試這個(主要是依賴注入)。我GOOGLE了很多網站,並做模擬試驗方法,在mvc4實體框架中的CRUD操作中的單元測試
http://www.codeproject.com/Articles/447988/How-to-Mock-Test-an-Entity-Framework-Model-First-P
,但沒有奏效。其實單元測試EF最好的方法是什麼?創建一個測試類或創建一個測試項目。這是我的粗體操作代碼,我該如何單元測試,請幫助我。
Member.cs
public class Member
{
[Key]
public int MemID {get;set;}
[Required]
[Display(Name = "Member Name")]
[StringLength(50)]
public string MemName { get; set; }
}
MemberController
public class MemberController : Controller
{
private SampleDataContext db = new SampleDataContext();
//
// GET: /Member/
public ActionResult Index()
{
return View(db.Members.ToList());
}
//
// GET: /Member/Details/5
public ActionResult Details(int id = 0)
{
Member member = db.Members.Find(id);
if (member == null)
{
return HttpNotFound();
}
return View(member);
}
//
// GET: /Member/Create
public ActionResult Create()
{
return View();
}
//
// POST: /Member/Create
[HttpPost]
public ActionResult Create(Member member)
{
if (ModelState.IsValid)
{
db.Members.Add(member);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(member);
}
//
// GET: /Member/Edit/5
public ActionResult Edit(int id = 0)
{
Member member = db.Members.Find(id);
if (member == null)
{
return HttpNotFound();
}
return View(member);
}
//
// POST: /Member/Edit/5
[HttpPost]
public ActionResult Edit(Member member)
{
if (ModelState.IsValid)
{
db.Entry(member).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(member);
}
//
// GET: /Member/Delete/5
public ActionResult Delete(int id = 0)
{
Member member = db.Members.Find(id);
if (member == null)
{
return HttpNotFound();
}
return View(member);
}
//
// POST: /Member/Delete/5
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id)
{
Member member = db.Members.Find(id);
db.Members.Remove(member);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
}
是的,你可以通過各種類型的測試來測試代碼。添加類庫並測試代碼的最簡單方法。換句話說,你可以使用NUnit來測試它。爲此,您必須添加某些dll文件才能使用NUnit。 – siddhesh
你能否更具描述性地描述你想在這裏測試什麼? –
@Dawid:我只是想測試每一個CRUD操作,並知道如何測試在EF – neel