views:

373

answers:

3

I've been trying to push my mentallity when developing at home to be geared more towards TDD and a bit DDD.

One thing I don't understand though is why you would create a fake repository to test against? I haven't really looked into it much but surely the idea of testing is to help decouple your code (giving you more flexability), trim down code needed and bring down the number of bugs.

So can someone fill in my foolish brain as to why some like to test fake repositories? I would have thought testing against a real database is a much better alternative to creating a fake one because then you KNOW that it works against your real world data store.

+18  A: 

The fake repository allows you to test just your application code.

The fake repository means an automated test can easily set up a known state in the repository.

The fake repository will be several orders of magnitude faster than a real database.

The fake repository is NOT a substitute for system testing that will include your database.

Giraffe
So creating a fake repository for the sake of adding and updating items to pass tests is pointless? It should only be used for testing your application code? If that is right I'll update this with the accepted answer.
John_
+5  A: 

As I see it there are two really big reasons why you test against faked resources:

  • It makes unit testing faster when you have a mocked up against slow I/O or database. This may not look like anything if you have a small test suite but when you're up to +500 unit tests it starts to make a difference. In such amount, tests that run against the database will start to take several seconds to do. Programmers are lazy and want things to go fast so if running a test suite takes more than 10 seconds then you won't be happy to do TDD anymore.
  • It enforces you to think about your code design to make changes easier. Design by contract and dependency injection also becomes so much easier to do if you've made implementation against interfaces or abstract classes. If done right such design makes it easier to comply to changes in your code.

The only drawback is the obvious one:

  • How can you be sure it really works?

...and that is what integration tests are for.

Spoike
+2  A: 

I upvoted Giraffe's answer, but want to add just a couple of points:

  • Each developer can use a mock/fake repository for her/his own unit testing without interfering with the tests being done by other developers on the same project.

  • Using a local mock/fake repository reinforces the user of a data abstraction layer, which is good design practice.

As an example, I've used something as simple as a HashMap to implement a mock of the data access layer. This makes it extremely easy for each unit test to ensure that exactly the necessary conditions exist for its purpose, and to verify that the right calls were made on the data access layer.

joel.neely