Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unit testing a unit of work

new to unit testing. I have a unit of work that I am trying to unit test. I am probably missing something simple here. I am trying to unit test the Commit method. I am using nunit and moq.

public class  UnitOfWork : IUnitOfWork
{
    private readonly DbContext _context;
    public UnitOfWork(DbContext ctx)
    {
        _context = ctx;
    }

    public void Commit()
    {
        _context.SaveChanges();
    }
}

What do I need to do to test this?

like image 801
Justin Avatar asked Jun 14 '11 20:06

Justin


Video Answer


2 Answers

You would insert a mock of the DBContext and then verify that the SaveChanges method is called on commit.

[Test]
public void Will_call_save_changes() {

  var mockContext = new Mock<DBContext>();
  var unitOfWork = new UnitOfWork(mockContext.Object);

  unitOfWork.Commit();


  mockContext.Verify(x => x.SaveChanges());

}
like image 104
Matthew Manela Avatar answered Oct 12 '22 07:10

Matthew Manela


You'll need to mock the DbContext, and then verify that SaveChanges was called. Something like Moq can help you here.

like image 20
Andy Avatar answered Oct 12 '22 06:10

Andy