我正在尝试研究 mvc4 中的实体框架。我在 EF 中使用 CRUD 操作创建了一个项目。现在我想对此进行单元测试(主要是依赖注入)。我搜索了很多网站,并尝试做模拟测试方法,
http://www.codeproject.com/Articles/447988/How-to-Mock-Test-an-Entity-Framework-Model-First-P
但它没有用。实际上,对 EF 进行单元测试的最佳方法是什么?为测试创建一个类或创建一个测试项目。这是我的crud操作代码,我该如何对它进行单元测试,请帮助我。
会员.cs
public class Member
{
[Key]
public int MemID {get;set;}
[Required]
[Display(Name = "Member Name")]
[StringLength(50)]
public string MemName { get; set; }
}
成员控制器
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);
}
}