Hacker News new | past | comments | ask | show | jobs | submit login

Oh god mocks/fakes/doubles. The best answer to that probably comes from The Art of Unit Testing as explained on SO: http://stackoverflow.com/a/33333064/2136440.

In short yea, you're right.




Generally speaking, with a mock you are not providing an implementation. You are simply making an assertion that something is called in a certain way. This is great for testing adaptors, for instance. Basically you are saying, "I expect to interact with another outside object in this way".

Stubs return canned data. This is great for testing that the calculations in your unit are correct without having to use the real collaborators. With stubs you are saying, "I expect my unit to produce this output from this input".

Fakes are objects that provide a working interface for your unit and often provide either stubs or mocks. It is not quite correct (IMHO) to say that a fake can be a stub or it can be a mock. It may also be used when you have highly coupled code and you just need the object that does intelligent things so that you can get to the meat of your test. This is a very common technique when you are trying to inject tests into legacy code. With a fake you are saying "I need to use a working collaborator, but I don't want to use the real collaborator for some reason" (usually because it is slow/dangerous/hard to create).

Like I said, fakes often contain/return stubs or mocks. A good example of a fake would be a fake that implemented a REST interface and returned canned data depending on what parameters you sent it. It would replace the exact same object with a REST interface that would be used to talk to the network.


Osherove's example on SO thread on mocks being troublemakers does not apply what adamconroy is asking, though.

Mocking libraries create dummy objects. They can't reproduce inner workings of mocked object unless you set it up to behave like that, which means you should duplicate the original which is pointless. You set up the mock to listen on it's entry points (and to return some predetermined answer), give it to your code under test, and expect the mock to be called in a certain way. This is testing the entry point of the mocked object, not it's internal workings. This way, you're expecting the code under test to behave according to a definition, so you're still testing your code, the way it's calling some other object gives you insights of your code's inner workings.


I was just saying his idea of what differentiates a mock from a fake was right!


that's a good thread.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: