Freigeben über


"Mocks: the code smell"

So I stole the title from this talk:
[View:https://www.youtube.com/watch?v=Giqewl1zT_A]

I have seen Arlo argue for his tests with simulators and I've always felt I shared his view on mocks. Or at least I share what I think is his view; that they should be avoided and only used under special circumstances. Kind of like nuclear weapons... But that is not important. My point was that before this talk I never understood exactly what Arlo was trying to say. What I learned from this talk made sense. Let me try to boil it down for you.

Designing an API where dependencies are given as interfaces is just bundling a bunch of delegates with a common name (IMyInterface). But when you test something you rarely use all the methods in your interface in every test. You also need to create an object that implements that interface. If you instead just use delegates for your dependencies then each API can easily be tested by only providing exactly what that API needs. Down to individual methods. I'm sure this makes writing unit tests way easier. Actually I know that...

However there is another thing that I think is not mentioned in the talk. If you provide all your dependencies as individual delegates you will sooner feel that an object has way to many dependencies and you will break it up. Think about it. An object or method that takes a single interface is not that bad. Not even if the interface has ten methods on it. But faking that sucker is going to be a pain unless you know for sure which of the ten methods you do not need to provide. But if the object or method takes ten delegates it is obvious that maybe it should be broken up in more smaller pieces. A design that is most likely to be preferred. Hence this pattern kind of encourages the same thing as object calisthenics rule #6; keep entities small.