Are mocks better than stubs?

前端 未结 6 938
梦毁少年i
梦毁少年i 2021-02-13 09:01

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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-13 09:44

    As the mantra goes 'Go with the simplest thing that can possibly work.'

    1. If fake classes can get the job done, go with them.
    2. If you need an interface with multiple methods to be mocked, go with a mock framework.

    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 or your implementation changes... your tests break. This is bad coz you'll spend additional time getting your tests to run instead of just getting your SUT to run. Tests should not be inappropriately intimate with the implementation.
    So use your best judgment.. I prefer mocks when it'll help save me writing-updating a fake class with n>>3 methods.

    Update Epilogue/Deliberation:
    (Thanks to Toran Billups for example of a mockist test. See below)
    Hi Doug, Well I think we've transcended into another holy war - Classic TDDers vs Mockist TDDers. I think I'm belong to the former.

    • If I am on test#101 Test_ExportProductList and I find I need to add a new param to IProductService.GetProducts(). I do that get this test green. I use a refactoring tool to update all other references. Now I find all the mockist tests calling this member now blow up. Then I have to go back and update all these tests - a waste of time. Why did ShouldPopulateProductsListOnViewLoadWhenPostBackIsFalse fail? Was it because the code is broken? Rather the tests are broken. I favor the one test failure = 1 place to fix. Mocking freq goes against that. Would stubs be better? If it I had a fake_class.GetProducts().. sure One place to change instead of shotgun surgery over multiple Expect calls. In the end it's a matter of style.. if you had a common utility method MockHelper.SetupExpectForGetProducts() - that'd also suffice.. but you'll see that this is uncommon.
    • If you place a white strip on the test name, the test is hard to read. Lot of plumbing code for the mock framework hides the actual test being performed.
    • requires you to learn this particular flavor of a mocking framework

提交回复
热议问题