Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
488 views
in Technique[技术] by (71.8m points)

mocking - Should you only mock types you own?

I read through TDD: Only mock types you own entry by Mark Needham and would like to know if this is best practice or not?

Please note that he is not against mocking, but against mocking directly - he does say that writing a wrapper and mocking that is fine.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

My answer is "no". You should mock anything that makes sense in the context of a given unit test. It should not matter if you "own" the mocked type or not.

These days, in a Java or .NET environment everything (and I really mean everything) can be easily mocked. So, there is no technical reason to go to the trouble of first writing extra wrapper code.


Some additional ideas I have been thinking about recently (November 2010), that show how illogical to "only mock types you own" can be:

  1. Suppose you do create a wrapper for a third-party API, and then you mock the wrapper in unit tests. Later, however, you figure the wrapper can be reused in another app, so you move it to a separate library. So now the wrapper is no longer "owned" by you (since it is used in multiple apps, potentially maintained by different teams). Should developers create a new wrapper for the old one?!? And keep doing it recursively, adding layer upon layer of essentially useless code?
  2. Suppose somebody else already created a nice wrapper for some non-trivial API and made it available as a reusable library. If said wrapper is just what I need for my specific use case, should I first create a wrapper for the wrapper, with a nearly identical API, just so I will "own" it?!?

For a concrete and realistic example, consider the Apache Commons Email API, which is nothing more than a wrapper for the standard Java Mail API. Since I don't own it, should I always create a wrapper for the Commons Email API, whenever I write unit tests for a class which needs to send e-mail?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...