O.O
O.O

Reputation: 11287

How to unit test Create POST?

How do I unit test that the journal entry was created correctly (added to the db with the correct values)?

    [HttpPost]
    public ActionResult Create(
        int journalId, 
        string text)
    {
        JournalEntry journalentry = new JournalEntry();
        journalentry.Text = text;
        if (ModelState.IsValid)
        {
            var journal = db.Journals.Find(journalId);               
            journalentry.Journal = journal;                
            db.JournalEntries.Add(journalentry);
            db.SaveChanges();
        }

        return View(journalentry);
    }

Upvotes: 2

Views: 127

Answers (1)

danludwig
danludwig

Reputation: 47375

You should not unit test against a real DbContext instance.

Your unit tests should instead mockup interfaces and inject them into the controller.

For example:

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);
    }
}

Your interface would look something like this:

public interface IJournalsRepository
{
    Journal FindJournal(int id);
    void Add(JournalEntry journalEntry);
    void SaveChanges();
}

You could unit test this like so (using Moq):

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());
}

Upvotes: 3

Related Questions