Are mocks better than stubs?

前端 未结 6 1443
予麋鹿
予麋鹿 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:59

    It's best to use a combination, and you'll have to use your own judgement. Here's the guidelines I use:

    • If making a call to external code is part of your code's expected (outward-facing) behavior, this should be tested. Use a mock.
    • If the call is really an implementation detail which the outside world doesn't care about, prefer stubs. However:
    • If you're worried that later implementations of the tested code might accidentally go around your stubs, and you want to notice if that happens, use a mock. You're coupling your test to your code, but it's for the sake of noticing that your stub is no longer sufficient and your test needs re-working.

    The second kind of mock is a sort of necessary evil. Really what's going on here is that whether you use a stub or a mock, in some cases you have to couple to your code more than you'd like. When that happens, it's better to use a mock than a stub only because you'll know when that coupling breaks and your code is no longer written the way your test thought it would be. It's probably best to leave a comment in your test when you do this so that whoever breaks it knows that their code isn't wrong, the test is.

    And again, this is a code smell and a last resort. If you find you need to do this often, try rethinking the way you write your tests.

提交回复
热议问题