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.
Mocking is a process used in unit testing when the unit being tested has external dependencies. The purpose of mocking is to isolate and focus on the code being tested and not on the behavior or state of external dependencies.
If the DTO has logic in it you might like to mock out, I would move the logic out of the DTO. To create DTO, I would do this from text, either in the test itself, or from an external file. You could use JSon, but if you don't use that already I would use XMLEncoder/XMLDecoder.
Mock will be created by Mockito. Here we've added two mock method calls, add() and subtract(), to the mock object via when(). However during testing, we've called subtract() before calling add(). When we create a mock object using create(), the order of execution of the method does not matter.
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:
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With