Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you mock UnitOfWork from Rhino.Commons?

My application is using Rhino.Commons - NHRepository and UnitOfWork. I like the With.Transaction() syntax for transactions and have been using it for some time.

But I ran into a problem - how do I mock a UnitOfWork for testing? Especially this is causing trouble for me:

With.Transaction(() => Repositories.TwinfieldSpooler.Update(spool));

I can mock repositories with Rhino.Mocks, but how can I easily mock UnitOfWork for this kind of code?

like image 762
Mateusz Kubiczek Avatar asked Dec 05 '25 15:12

Mateusz Kubiczek


1 Answers

With.Transaction uses UnitOfWork.Current property. UnitOfWork is a static class -- you can't mock it with RhinoMocks.

UnitOfWork.Current is a public static property, so you can swap it out. Unfortunately, the setter is internal.

I see 3 options for you:

  • Modify the Rhino.Commons source to make UnitOfWork.Current setter public, and set it in your unit test.

  • Use reflection to set the UnitOfWork.Current to your fake unit of work.

  • Since UnitOfWork.Current internally uses Local.Data to find the current transaction, you should be able to go:

    Rhino.Commons.Local.Data[UnitOfWork.CurrentUnitOfWorkKey] = myFakeUnitOfWork;

One bit of good news is that UnitOfWork.Current is an IUnitOfWork, and RhinoMocks can easily fake interfaces.

I must finish by saying, I'm not very familiar with Rhino.Commons, so Ayende might have built a proper way of faking UnitOfWork. If this is super-important to you, you ought to ask in the Rhino discussion groups.

like image 150
Judah Gabriel Himango Avatar answered Dec 09 '25 18:12

Judah Gabriel Himango



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!