Are mocks better than stubs?

前端 未结 6 1447
予麋鹿
予麋鹿 2021-02-13 09:27

A while ago I read the Mocks Aren\'t Stubs article by Martin Fowler and I must admit I\'m a bit scared of external dependencies with regards to added complexity so I would like

6条回答
  •  误落风尘
    2021-02-13 09:56

    I generally prefer to use mocks because of Expectations. When you call a method on a stub that returns a value, it typically just gives you back a value. But when you call a method on a mock, not only does it return a value, it also enforces the expectation that you set up that the method was even called in the first place. In other words, if you set up an expectation and then don't call that method, an exception gets thrown. When you set an expectation, you are essentially saying "If this method doesn't get called, something went wrong." And the opposite is true, if you call a method on a mock and did not set an expectation, it will throw an exception, essentially saying "Hey, what are you doing calling this method when you didn't expect it."

    Sometimes you don't want expectations on every method you're calling, so some mocking frameworks will allow "partial" mocks that are like mock/stub hybrids, in that only the expectations you set are enforced, and every other method call is treated more like a stub in that it just returns a value.

    One valid place to use stubs I can think of off the top, though, is when you are introducing testing into legacy code. Sometimes it's just easier to make a stub by subclassing the class you are testing than refactoring everything to make mocking easy or even possible.

    And to this...

    Avoid using mocks always because they make tests brittle. Your tests now have intricate knowledge of the methods called by the implementation, if the mocked interface changes... your tests break. So use your best judgment..<

    ...I say if my interface changes, my tests had better break. Because the whole point of unit tests is that they accurately test my code as it exists right now.

提交回复
热议问题