Rhino Fakes, or "How to Create Fake Objects In Rhino Mocks"
In the comments of my recent Rhino Mocks post, James Kovacs pointed me to this post from Oren on interaction-based testing. In it, Oren gives guidelines for using Rhino Mocks to create fake objects. Namely, use DynamicMock instead of CreateMock and use SetupResult instead of Expect or LastCall.
So that said, here is my original test:
[ Test ]
public void JobNumberShouldNotBeZeroAfterReconstitution( )
{
int jobNumber = 42;
fakeAJob( jobNumber );
IJob job = jobRepository.GetJob( jobNumber );
Assert.AreEqual( job.JobNumber, jobNumber );
}
private void fakeAJob( int jobNumber ) { Job job = jobFactory.CreateJob( ); JobRepository.SetFieldWhenReconstitutingFromPersistence( job, "jobNumber", jobNumber ); jobRepository.AddJob( job ); }
This is following pretty closely with Jimmy Nilsson's Applying Domain-Driven Design, at least in the early chapters which I'm currently scouring, including the problem he mentions about creating a job with an order number without specifying it in the constructor. SetFieldWhenReconstitutingFromPersistence uses reflection to set the field which he knows is bad but I haven't got to that part of the book yet.
Instead, I thought I'd have a go at creating a fake object in Rhino Mocks, leading to the following revised code:
[ Test ]
public void JobNumberShouldNotBeZeroAfterReconstitution( )
{
int jobNumber = 42;
MockRepository mockery = new MockRepository( );
IJob fakeJob = mockery.DynamicMock<IJob>( );
SetupResult.For( fakeJob.JobNumber ).Return( jobNumber );
jobRepository.AddJob( fakeJob );
IJob job = jobRepository.GetJob( jobNumber );
Assert.AreEqual( job.JobNumber, jobNumber );
}
Both tests pass which was nice to see. I'm throwing this out partially as an example of how to create a fake with Rhino Mocks (because I had trouble finding any explicit ones) but mostly to get confirmation that I'm still testing what I want to test, which I think I am.