Archives

  • Categories

  • Mocking LightSpeed Units Of Work

    One of my colleagues asked me the other day how he could mock a LightSpeed UnitOfWork. Apparently he couldn’t find any good examples out there on the InterWeb so I thought I’d post this short code sample to show how its done.

    The most important thing is that you should not create your UnitOfWork yourself but use the CreateUnitOfWork() factory method on your LightSpeedContext. See code example below.

    using (var unitOfWork = Repository.Context.CreateUnitOfWork())
     {
            var customerOverEighteenYearsOld = unitOfWork
                                  .Customers
                                  .Where(customer => customer.Age > 18);
           return customerOverEighteenYearsOld.ToList();
     }
    

    Now if we wanted to test this code by mocking our UnitOfWork we can substitute our IQueryable<Customers> with an in memory collection rather than hitting the database directly.

    So our unit test setup code would look something like this. The example below uses Rhino Mocks to mock the Unit Of Work.

    [SetUp]
    public void TestSetUp()
    {
             // Customer Collection
             var customers = new List<Customer>{
                                    new Customer{Age = 10},
                                    new Customer{Age = 18}
                                    }; 
    
             var unitOfWorkFactory = MockRepository.GenerateStub<IUnitOfWorkFactory>();
             var unitOfWork = MockRepository.GenerateStub<CustomersUnitOfWork>(); 
    
             // Replace the normal UnitOfWorkFactory with our implementation.
             Repository.Context.UnitOfWorkFactory = _unitOfWorkFactory; 
    
             // Stub the behaviour of our unit of work factory to
             // return our mocked UnitOfWork
             unitOfWorkFactory
                        .Stub(uowf => uowf.Create(Arg<LightSpeedContext>.Is.Anything))
                        .Return(unitOfWork ); 
    
             // Stub our unit of work to return our in memory customer collection.
             unitOfWork.Stub(uow => uow.Customers()).Return(customers);
    }
    

    So all we really need to do is to mock our LightSpeed UnitOfWork Factory replacing the default factory on our LightSpeed Context with our mocked version.  

    We can then stub out the Create method on our mocked UnitOfWork factory to return our own implementation of our UnitOfWork (which is also a mock).  

    We can now get our UnitOfWork to behave as we want it to without ever having to hit a database.

    kick it on DotNetKicks.com

    One Response to “Mocking LightSpeed Units Of Work”


    1. Carlos DeAngulo says:

      Thank you!!! You saved me hours upon hours of work. I had attempted to get this working for a week, until I found your post. Now my unit testing is working.

      Thank you.

    Leave a Reply