<p>A while ago I read the <a href="http://www.martinfowler.com/articles/mocksArentStubs.html" rel="nofollow noreferrer">Mocks Aren't Stubs</a> 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 to ask:</p>

<p>What is the best method to use when unit testing?</p>

<p>Is it better to always use a mock framework to automatically mock the dependencies of the method being tested, or would you prefer to use simpler mechanisms like for instance test stubs?</p>

[{'answer_id': 47766, 'author': 'David Schmitt', 'author_id': 4918, 'author_profile': 'https://Stackoverflow.com/users/4918', 'pm_score': 1, 'selected': False, 'text': '<p>Read Luke Kanies\' discussion of exactly this question in <a href="http://www.madstop.com/ruby/jay_and_i_converge_on_testing.html" rel="nofollow noreferrer">this blog post</a>. He references <a href="http://blog.jayfields.com/2008/05/using-stubs-to-capture-test-essence.html" rel="nofollow noreferrer">a post from Jay Fields</a> which even suggests that using [a equivalent to ruby\'s/mocha\'s] stub_everything is preferrable to make the tests more robust. To quote Fields\' final words: "Mocha makes it as easy to define a mock as it is to define a stub, but that doesn\'t mean you should always prefer mocks. In fact, I generally prefer stubs and use mocks when necessary."</p>\n'}, {'answer_id': 47781, 'author': 'Gishu', 'author_id': 1695, 'author_profile': 'https://Stackoverflow.com/users/1695', 'pm_score': 5, 'selected': True, 'text': "<p>As the mantra goes 'Go with the simplest thing that can possibly work.'</p>\n\n<ol>\n<li>If fake classes can get the job done, go with them. </li>\n<li>If you need an interface with multiple methods to be mocked, go with a mock framework.</li>\n</ol>\n\n<p>Avoid using mocks <em>always</em> 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. <em>Tests should not be inappropriately intimate with the implementation.</em><br>\nSo use your best judgment.. I prefer mocks when it'll help save me writing-updating a fake class with n>>3 methods.</p>\n\n<p><strong>Update</strong> Epilogue/Deliberation:<br>\n(Thanks to Toran Billups for example of a mockist test. See below)<br>\nHi Doug, Well I think we've transcended into another holy war - Classic TDDers vs Mockist TDDers. I think I'm belong to the former.   </p>\n\n<ul>\n<li>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 <em>one test failure = 1 place to fix</em>. 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. </li>\n<li>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.</li>\n<li>requires you to learn this particular flavor of a mocking framework</li>\n</ul>\n"}, {'answer_id': 47787, 'author': 'Toran Billups', 'author_id': 2701, 'author_profile': 'https://Stackoverflow.com/users/2701', 'pm_score': 2, 'selected': False, 'text': "<p>It just depends on what type of testing you are doing.  If you are doing behavior based testing you might want a dynamic mock so you can verify that some interaction with your dependancy occurs.  But if you are doing state based testing you might want a stub so you verify values/etc</p>\n\n<p>For example, in the below test you notice that I stub out the view so I can verify a property value is set (state based testing).  I then create a dynamic mock of the service class so I can make sure a specific method gets called during the test (interaction / behavior based testing).</p>\n\n<pre><code>&lt;TestMethod()&gt; _\nPublic Sub Should_Populate_Products_List_OnViewLoad_When_PostBack_Is_False()\n    mMockery = New MockRepository()\n    mView = DirectCast(mMockery.Stub(Of IProductView)(), IProductView)\n    mProductService = DirectCast(mMockery.DynamicMock(Of IProductService)(), IProductService)\n    mPresenter = New ProductPresenter(mView, mProductService)\n    Dim ProductList As New List(Of Product)()\n    ProductList.Add(New Product())\n    Using mMockery.Record()\n        SetupResult.For(mView.PageIsPostBack).Return(False)\n        Expect.Call(mProductService.GetProducts()).Return(ProductList).Repeat.Once()\n    End Using\n    Using mMockery.Playback()\n        mPresenter.OnViewLoad()\n    End Using\n    'Verify that we hit the service dependency during the method when postback is false\n    Assert.AreEqual(1, mView.Products.Count)\n    mMockery.VerifyAll()\nEnd Sub\n</code></pre>\n"}, {'answer_id': 47795, 'author': 'Peeja', 'author_id': 4937, 'author_profile': 'https://Stackoverflow.com/users/4937', 'pm_score': 2, 'selected': False, 'text': "<p>It's best to use a combination, and you'll have to use your own judgement.  Here's the guidelines I use:</p>\n\n<ul>\n<li>If making a call to external code is part of your code's expected (outward-facing) behavior, this should be tested.  Use a mock.</li>\n<li>If the call is really an implementation detail which the outside world doesn't care about, prefer stubs.  However:</li>\n<li>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.</li>\n</ul>\n\n<p>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.</p>\n\n<p>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.</p>\n"}, {'answer_id': 47966, 'author': 'Doug R', 'author_id': 3271, 'author_profile': 'https://Stackoverflow.com/users/3271', 'pm_score': 3, 'selected': False, 'text': '<p>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."  </p>\n\n<p>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.</p>\n\n<p>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.</p>\n\n<p>And to this...</p>\n\n<blockquote>\n  <p>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..&lt;</p>\n</blockquote>\n\n<p>...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.</p>\n'}, {'answer_id': 894395, 'author': 'Steve Freeman', 'author_id': 75123, 'author_profile': 'https://Stackoverflow.com/users/75123', 'pm_score': 2, 'selected': False, 'text': '<p>Never mind Statist vs. Interaction. Think about the Roles and Relationships. If an object collaborates with a neighbour to get its job done, then that relationship (as expressed in an interface) is a candidate for testing using mocks. If an object is a simple value object with a bit of behaviour, then test it directly. I can\'t see the point of writing mocks (or even stubs) by hand. That\'s how we all started and refactored away from that.</p>\n\n<p>For a longer discussion, consider taking a look at <a href="http://www.mockobjects.com/book" rel="nofollow noreferrer">http://www.mockobjects.com/book</a></p>\n'}]
['https://Stackoverflow.com/questions/47749', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1324220/']