That’s right, I said it, I’ve been doing it, and I abso-effin-lutely love it.
A few months ago my co-worker, Troy, posted a question on Stack Overflow. We were doing integration testing on a project we were working on, and as the object graph grew larger, the code required to test query logic became painful. Since I am a sissy and don’t like pain, Troy asked the question on SO about how we might do it less painfully, and we got this answer, and it totally changed our TDD/BDD lives.
The answer came from Garry Shutler, here and I’ll just sort of re-iterate it.
We created a base Interface for our repositories IRepository<T>, with a method IQueryable<T> All(). like so:
1: public interface IRepository<T>
2: {
3: IQueryable<T> All();
4: // whatever else you want
5: }
Then we implement it like so:
1: public IQueryable<T> All()
2: {
3: return session.Linq<T>();
4: }
We can then mock the IRepository<T>:
1: _repository = MockRepository.GenerateMock<IRepository<Customer>>();
Then Stub it to return a predefined list of objects that we are searching
1: _repository.Stub(repo => repo.All()).Return(TestCustomers.All().AsQueryable());
Then we can test the login of a Customer search by:
1: [Test]
2: public void should_return_customers_matching_first_name_last_name_and_dob()
3: {
4: Assert.That(_returnedMatches.Contains(_firstNameLastNameDOBMatch));
5: }
Many thanks to Garry for all the time he saved us, I immediately subscribed to his blog and have not been disappointed. I hope this helps someone as much as it has helped us.
~L