Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TDD: Test first or Repository pattern first

I'm new to TDD and I have a question with concept. It's said in TDD no code is written without writing test first. We usually need Repository pattern to mock objects and to be able to implement testing. My question is: should we first implement Repository pattern ? If yes, what happens to writing test first ? If no, how can we mock objects without using Repository pattern ?

I would appreciate your taking time.

like image 400
pers Avatar asked Oct 12 '25 13:10

pers


1 Answers

If you intend to develop using TDD there is no doubt that you have to create your tests first.

It will let you implement the repository pattern naturally and will make your life easier as the repository pattern will make unit testing less painful.

Even the TDD test cycle enforces this order:

  1. Write a failing acceptance test
  2. Write a failing unit test
  3. Make the failing test pass
  4. Refactor
  5. Repeat steps 2-4 until the failing acceptance test passes

The repository pattern would be introduced in steps 3 and 4. when you actually write your code.

While I prefer those patterns to be introduced in step 4, some other people would just jump ahead and implement it in step 3. It's a matter of style, but I prefer the more complex code to be introduced once the unit test passes.

If you want to get a deeper understanding of this topic, there are some formidable books about refactoring, but one might be especially interesting for you as it logically binds refactoring and design patterns. Refactoring to Patterns

I have implemented the repository pattern in TDD development myself a few months ago and it worked out just fine.

I think this is an excellent question, so thanks a lot for asking it.

like image 129
Jesko R. Avatar answered Oct 16 '25 09:10

Jesko R.