您不应针对真实的 DbContext 实例进行单元测试。
您的单元测试应该改为模拟接口并将它们注入控制器。
例如:
public class JournalsController : Controller
{
private readonly IJournalsRespository _journalsDb;
public JournalsController(IJournalsRepository journalsDb)
{
_journalsDb = journalsDb
}
[HttpPost]
public ActionResult Create(int journalId, string text)
{
JournalEntry journalentry = new JournalEntry();
journalentry.Text = text;
if (ModelState.IsValid)
{
var journal = _journalsDb.FindJournal(journalId);
journalentry.Journal = journal;
_journalsDb.Add(journalentry);
_journalsDb.SaveChanges();
}
return View(journalentry);
}
}
你的界面看起来像这样:
public interface IJournalsRepository
{
Journal FindJournal(int id);
void Add(JournalEntry journalEntry);
void SaveChanges();
}
您可以像这样对它进行单元测试(使用最小起订量):
public void Create()
{
var db = new Mock<IJournalsRepository>();
db.Setup(m => m.FindJournal(7)).Returns(new Journal());
var controller = new JournalsController(db.Object);
controller.Create(7, "test");
db.Verify(m => m.FindJournal(7), Times.Once());
db.Verify(m => m.Add(It.IsAny<JournalEntry>()), Times.Once());
db.Verify(m => m.SaveChanges(), Times.Once());
}