<p>I have a basic understanding of mock and fake objects, but I'm not sure I have a feeling about when/where to use mocking - especially as it would apply to this scenario <a href="https://stackoverflow.com/questions/37375/how-do-i-unit-test-a-wcf-service"><strong>here</strong></a>.</p>

[{'answer_id': 38194, 'author': 'Toran Billups', 'author_id': 2701, 'author_profile': 'https://Stackoverflow.com/users/2701', 'pm_score': 3, 'selected': False, 'text': '<p>You should mock an object when you have a dependency in a unit of code you are trying to test that needs to be "just so".  </p>\n\n<p>For example, when you are trying to test some logic in your unit of code but you need to get something from another object and what is returned from this dependency might affect what you are trying to test - mock that object.</p>\n\n<p>A great podcast on the topic can be found <a href="http://www.hanselminutes.com/default.aspx?showID=43" rel="noreferrer">here</a></p>\n'}, {'answer_id': 38256, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 8, 'selected': True, 'text': "<p>A unit test should test a single codepath through a single method.  When the execution of a method passes outside of that method, into another object, and back again, you have a dependency.</p>\n<p>When you test that code path with the actual dependency, you are not unit testing; you are integration testing.  While that's good and necessary, it isn't unit testing.</p>\n<p>If your dependency is buggy, your test may be affected in such a way to return a false positive.  For instance, you may pass the dependency an unexpected null, and the dependency may not throw on null as it is documented to do.  Your test does not encounter a null argument exception as it should have, and the test passes.</p>\n<p>Also, you may find its hard, if not impossible, to reliably get the dependent object to return exactly what you want during a test.  That also includes throwing expected exceptions within tests.</p>\n<p>A mock replaces that dependency.  You set expectations on calls to the dependent object, set the exact return values it should give you to perform the test you want, and/or what exceptions to throw so that you can test your exception handling code.  In this way you can test the unit in question easily.</p>\n<p>TL;DR:  Mock every dependency your unit test touches.</p>\n"}, {'answer_id': 38260, 'author': 'Jan Soltis', 'author_id': 3997, 'author_profile': 'https://Stackoverflow.com/users/3997', 'pm_score': 8, 'selected': False, 'text': '<p>Mock objects are useful when you want to <strong>test interactions</strong> between a class under test and a particular interface.</p>\n<p>For example, we want to test that method <code>sendInvitations(MailServer mailServer)</code> calls <code>MailServer.createMessage()</code> exactly once, and also calls <code>MailServer.sendMessage(m)</code> exactly once, and no other methods are called on the <code>MailServer</code> interface. This is when we can use mock objects.</p>\n<p>With mock objects, instead of passing a real <code>MailServerImpl</code>, or a test <code>TestMailServer</code>, we can pass a mock implementation of the <code>MailServer</code> interface. Before we pass a mock <code>MailServer</code>, we &quot;train&quot; it, so that it knows what method calls to expect and what return values to return. At the end, the mock object asserts, that all expected methods were called as expected.</p>\n<p>This sounds good in theory, but there are also some downsides.</p>\n<h3>Mock shortcomings</h3>\n<p>If you have a mock framework in place, you are tempted to use mock object <em>every time</em> you need to pass an interface to the class under the test. This way you end up <strong>testing interactions even when it is not necessary</strong>. Unfortunately, unwanted (accidental) testing of interactions is bad, because then you\'re testing that a particular requirement is implemented in a particular way, instead of that the implementation produced the required result.</p>\n<p>Here\'s an example in pseudocode. Let\'s suppose we\'ve created a <code>MySorter</code> class and we want to test it:</p>\n<pre><code>// the correct way of testing\ntestSort() {\n    testList = [1, 7, 3, 8, 2] \n    MySorter.sort(testList)\n\n    assert testList equals [1, 2, 3, 7, 8]\n}\n\n\n// incorrect, testing implementation\ntestSort() {\n    testList = [1, 7, 3, 8, 2] \n    MySorter.sort(testList)\n\n    assert that compare(1, 2) was called once \n    assert that compare(1, 3) was not called \n    assert that compare(2, 3) was called once \n    ....\n}\n</code></pre>\n<p>(In this example we assume that it\'s not a particular sorting algorithm, such as quick sort, that we want to test; in that case, the latter test would actually be valid.)</p>\n<p>In such an extreme example it\'s obvious why the latter example is wrong. When we change the implementation of <code>MySorter</code>, the first test does a great job of making sure we still sort correctly, which is the whole point of tests - they allow us to change the code safely. On the other hand, the latter test <em>always</em> breaks and it is actively harmful; it hinders refactoring.</p>\n<h3>Mocks as stubs</h3>\n<p>Mock frameworks often allow also less strict usage, where we don\'t have to specify exactly how many times methods should be called and what parameters are expected; they allow creating mock objects that are used as <a href="http://martinfowler.com/articles/mocksArentStubs.html" rel="noreferrer">stubs</a>.</p>\n<p>Let\'s suppose we have a method <code>sendInvitations(PdfFormatter pdfFormatter, MailServer mailServer)</code> that we want to test. The <code>PdfFormatter</code> object can be used to create the invitation. Here\'s the test:</p>\n<pre><code>testInvitations() {\n   // train as stub\n   pdfFormatter = create mock of PdfFormatter\n   let pdfFormatter.getCanvasWidth() returns 100\n   let pdfFormatter.getCanvasHeight() returns 300\n   let pdfFormatter.addText(x, y, text) returns true \n   let pdfFormatter.drawLine(line) does nothing\n\n   // train as mock\n   mailServer = create mock of MailServer\n   expect mailServer.sendMail() called exactly once\n\n   // do the test\n   sendInvitations(pdfFormatter, mailServer)\n\n   assert that all pdfFormatter expectations are met\n   assert that all mailServer expectations are met\n}\n</code></pre>\n<p>In this example, we don\'t really care about the <code>PdfFormatter</code> object so we just train it to quietly accept any call and return some sensible canned return values for all methods that <code>sendInvitation()</code> happens to call at this point. How did we come up with exactly this list of methods to train? We simply ran the test and kept adding the methods until the test passed. Notice, that we trained the stub to respond to a method without having a clue why it needs to call it, we simply added everything that the test complained about. We are happy, the test passes.</p>\n<p>But what happens later, when we change <code>sendInvitations()</code>, or some other class that <code>sendInvitations()</code> uses, to create more fancy pdfs? Our test suddenly fails because now more methods of <code>PdfFormatter</code> are called and we didn\'t train our stub to expect them. And usually it\'s not only one test that fails in situations like this, it\'s any test that happens to use, directly or indirectly, the <code>sendInvitations()</code> method. We have to fix all those tests by adding more trainings. Also notice, that we can\'t remove methods no longer needed, because we don\'t know which of them are not needed. Again, it hinders refactoring.</p>\n<p>Also, the readability of test suffered terribly, there\'s lots of code there that we didn\'t write because of we wanted to, but because we had to; it\'s not us who want that code there. Tests that use mock objects look very complex and are often difficult to read. The tests should help the reader understand, how the class under the test should be used, thus they should be simple and straightforward. If they are not readable, nobody is going to maintain them; in fact, it\'s easier to delete them than to maintain them.</p>\n<p>How to fix that? Easily:</p>\n<ul>\n<li>Try using real classes instead of mocks whenever possible. Use the real <code>PdfFormatterImpl</code>. If it\'s not possible, change the real classes to make it possible. Not being able to use a class in tests usually points to some problems with the class. Fixing the problems is a win-win situation - you fixed the class and you have a simpler test. On the other hand, not fixing it and using mocks is a no-win situation - you didn\'t fix the real class and you have more complex, less readable tests that hinder further refactorings.</li>\n<li>Try creating a simple test implementation of the interface instead of mocking it in each test, and use this test class in all your tests. Create <code>TestPdfFormatter</code> that does nothing. That way you can change it once for all tests and your tests are not cluttered with lengthy setups where you train your stubs.</li>\n</ul>\n<p>All in all, mock objects have their use, but when not used carefully, <strong>they often encourage bad practices, testing implementation details, hinder refactoring and produce difficult to read and difficult to maintain tests</strong>.</p>\n<p>For some more details on shortcomings of mocks see also <a href="http://www.oracle.com/technetwork/articles/entarch/mock-shortcomings-082129.html" rel="noreferrer">Mock Objects: Shortcomings and Use Cases</a>.</p>\n'}, {'answer_id': 38433, 'author': 'Orion Edwards', 'author_id': 234, 'author_profile': 'https://Stackoverflow.com/users/234', 'pm_score': 6, 'selected': False, 'text': '<p>Rule of thumb:</p>\n\n<p>If the function you are testing needs a complicated object as a parameter, and it would be a pain to simply instantiate this object (if, for example it tries to establish a TCP connection), use a mock.</p>\n'}]
['https://Stackoverflow.com/questions/38181', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/781/']