Unit Testing: Explain the usefulness of Mock Objects [duplicate]
Possible Duplicate:
What is Object Mock开发者_如何学Going and when do I need it?
You might indeed start writing tests for B and implementing B as soon as you know you need it and then come back to A. But when you come back to A you might want to use a mock for B so that your test for A is really testing A and its interactions with B.
Part of the reason for this is there might be another class C that B uses to do some of its work. If you want to test A using a real B, you'll also need C, and of course the difficulty can extend further.
Using mocks you can make your test check only that A calls B methods when it should and deals properly with the responses that you tell your mock to give, rather than depending on a real implementation of B.
To learn better how to use Mocks and in general TDD I recommend you nat pryce blog and his book http://www.natpryce.com/
Generally speaking it's not a good idea to use too much mocks. Use them when you have to isolate layers of your applications (db and view i.e.) or external (slow) system.
Writing mocks could make your tests hard to read, so it's better not abuse them.
The idea of the mock objects is that testing of A should not depend on testing of B (that's why it is called "unit" testing - you test the code in separate independent units). If A uses B, then it is hard to test if A works right without depending on B working right - unless you replace B with some "mock" object that knows to give "right" responses on "right" requests and detect "wrong" requests. This way if something breaks you know it's something wrong with A and not with B. As for development, it sometimes can happen that you don't know yet how exactly B is implemented - e.g., B is an interface with some webservice that you don't know full specifics yet, but you want starting developing your business logic in A and for now you don't care how login parameters for webservice are called or in which format it accepts the argument. You can then create "mock" B, have A worked out and then add B independently. That would also make easier to have B support other formats, etc. - since you wrote it from the beginning in a way generic enough to abstract the details away.
Mock objects are an interesting idea but they are in conflict with the concept of unit testing. If class A uses class B, it is really integrating logic in class A and B. In this case, class A is not a candidate for unit testing, but a candidate for integration testing. Unit tests are only for some classes, not all, as many so-called TDD experts believe.
精彩评论