14

I've read a lot of things about TDD but I still have doubts. For example, I have these class diagrams:

enter image description here

It's a simple example, just to learn about TDD and mock objects.

Which test should I write first? Product, then Line and last, Order? If I do that, should I use Line and Product to test Order or should I use Mock Objects? When should I use Mock Objects? Should I use UML with XP and TDD?

I don't get these things yet.

Zanon
  • 329

4 Answers4

10

Judging from the diagram, Product is a dumb data class, with no functionality to test. So I would start writing tests for (and implementing, TDD style) first Line and then Order, up the dependency ladder. It is usually sensible to have your lower level classes tested before starting work on higher level classes (i.e. which depend on the lower level). This makes catching bugs more efficient.

Whether you need to use mock objects depends on the actual dependencies of the tested class. If these are simple classes which you can easily instantiate and set up with any desired data/state required for your tests, you need no mocks. (This seems to be the case for your example design here.) However, if any of the dependencies is difficult to initialize / has extensive dependencies itself / has undesirable side effects / depends on an external resource such as a DB, then it makes sense to use a mock object instead.

4

I don't see much need for mock objects here. As pointed out by others, you need those mostly if dependencies are difficult to set up.

For example we used them with Ruby on Rails projects when we tested controllers and needed a user login that would have required a call to another controller and storing part of it's information in a cookie. In this case it's helpful to mock a logged in user that returns true, when asked about a certain access privilege.

2

"TDD is primarily a design technique with a side effect of ensuring that your source code is thoroughly unit tested" -- Scott W. Ambler

The idea is to find the design by writing unit tests. In your case, it seems you already have the design in place, which kinda defeats the purpose of TDD (assuming your design is final).

Regarding mocking. If you want to mock, I suggest you mock Product when writing tests for Line and mock Line when testing Order. But it may be overkill here. I personally try to limit mocking as much as possible, and use it to decouple dependencies on external classes (such as database instances).

2

Normally for testing you want to isolate the system/object under test, so you would mock anything that is outside of that. So using your class diagram, when testing an order object, use a mock for the line object. When testing Line, use a mock for Order and Product. When testing product, use mock for Line.

BlackICE
  • 2,425