We had a discussion today on how a test can tell you that something is off with your design. If a feature is hard to test you should listen carefully because your tests might be telling you something. The piece of code we where discussing is setting up return values for queries against our persistent store.

Stub(x=>x.Query(Arg<Func<Customer,bool>>.Is.Anything)) .Return(new[] { customer });

As you can see we have to specify the input to our query method using some hairy nested generics. Our test was just trying to return a specific customer when the repository was queried so having go through all the generic mumbo jumbo just felt wrong. This lead us into changing our old Query method

IEnumerable<T> Query<T>(Func<T, bool> criteria);


To use the query object pattern

IQueryResult<T> Query<T>(IQuery<T> query);

With this is place we can encapsulate our queries in separate classes implementing IQuery and there by adhering to the Single Responsibility Principle. As an added bonus our queries can now be reused instead of copy and pasted everywhere.

And the test?

This change in design allowed our test to focus on the right thing. That is:  “given the query GetCustomerByCrmIdOrOrgNr return this active customer”.

Stub<IRepository>(x => x.Query(Arg<GetCustomerByCrmIdOrOrgNr>.Is.Anything))
.Return(new List<Customer>{ activeCustomer }.ToLinqResult());


This did also allow us to refactor the test a bit further:

QueryFor<GetCustomerByCrmIdOrOrgNr>()
.Return(activeCustomer.AsLinqResult());

Ah, that’s more like it!

Final note:

We’re packaging our IRepository implementation into a public project that soon will be published on our github account.