<p>I'm sure most of you are writing lots of automated tests and that you also have run into some common pitfalls when unit testing. </p>

<p>My question is do you follow any rules of conduct for writing tests in order to avoid problems in the future? To be more specific: What are the <strong>properties of good unit tests</strong> or how do you write your tests?</p>

<p>Language agnostic suggestions are encouraged.</p>

[{'answer_id': 61410, 'author': 'Mendelt', 'author_id': 3320, 'author_profile': 'https://Stackoverflow.com/users/3320', 'pm_score': 4, 'selected': False, 'text': "<p>Keep these goals in mind (adapted from the book xUnit Test Patterns by Meszaros)</p>\n\n<ul>\n<li>Tests should reduce risk, not\nintroduce it.</li>\n<li>Tests should be easy to run.</li>\n<li>Tests should be easy to maintain as\nthe system evolves around them</li>\n</ul>\n\n<p>Some things to make this easier:</p>\n\n<ul>\n<li>Tests should only fail because of\none reason.</li>\n<li>Tests should only test one thing</li>\n<li>Minimize test dependencies (no\ndependencies on databases, files, ui\netc.)</li>\n</ul>\n\n<p>Don't forget that you can do intergration testing with your xUnit framework too <strong>but keep intergration tests and unit tests separate</strong></p>\n"}, {'answer_id': 61412, 'author': 'Sören Kuklau', 'author_id': 1600, 'author_profile': 'https://Stackoverflow.com/users/1600', 'pm_score': 5, 'selected': False, 'text': "<ol>\n<li><strong>Don't write ginormous tests.</strong> As the 'unit' in 'unit test' suggests, make each one as <em>atomic</em> and <em>isolated</em> as possible. If you must, create preconditions using mock objects, rather than recreating too much of the typical user environment manually.</li>\n<li><strong>Don't test things that obviously work.</strong> Avoid testing the classes from a third-party vendor, especially the one supplying the core APIs of the framework you code in. E.g., don't test adding an item to the vendor's Hashtable class.</li>\n<li><strong>Consider using a code coverage tool</strong> such as NCover to help discover edge cases you have yet to test.</li>\n<li><strong>Try writing the test <em>before</em> the implementation.</strong> Think of the test as more of a specification that your implementation will adhere to. Cf. also behavior-driven development, a more specific branch of test-driven development.</li>\n<li><strong>Be consistent.</strong> If you only write tests for some of your code, it's hardly useful. If you work in a team, and some or all of the others don't write tests, it's not very useful either. Convince yourself and everyone else of the importance (and <em>time-saving</em> properties) of testing, or don't bother.</li>\n</ol>\n"}, {'answer_id': 61415, 'author': 'Rob Wells', 'author_id': 2974, 'author_profile': 'https://Stackoverflow.com/users/2974', 'pm_score': 3, 'selected': False, 'text': '<p>What you\'re after is delineation of the behaviours of the class under test.</p>\n<ol>\n<li>Verification of expected behaviours.</li>\n<li>Verification of error cases.</li>\n<li>Coverage of all code paths within the class.</li>\n<li>Exercising all member functions within the class.</li>\n</ol>\n<p>The basic intent is increase your confidence in the behaviour of the class.</p>\n<p>This is especially useful when looking at refactoring your code. Martin Fowler has an interesting <a href="http://martinfowler.com/distributedComputing/duckling.pdf" rel="nofollow noreferrer">article</a> regarding testing over at his web site.</p>\n<p>HTH.</p>\n<p>cheers,</p>\n<p>Rob</p>\n'}, {'answer_id': 61416, 'author': 'Quibblesome', 'author_id': 1143, 'author_profile': 'https://Stackoverflow.com/users/1143', 'pm_score': 3, 'selected': False, 'text': '<p>Test should originally fail. Then you should write the code that makes them pass, otherwise you run the risk of writing a test that is bugged and always passes.</p>\n'}, {'answer_id': 61417, 'author': 'Alotor', 'author_id': 2937, 'author_profile': 'https://Stackoverflow.com/users/2937', 'pm_score': 2, 'selected': False, 'text': "<ul>\n<li>Unit Testing just tests the external API of your Unit, you shouldn't test internal behaviour.</li>\n<li>Each test of a TestCase should test one (and only one) method inside this API.\n\n<ul>\n<li>Aditional Test Cases should be included for failure cases.</li>\n</ul></li>\n<li>Test the coverage of your tests: Once a unit it's tested, the 100% of the lines inside this unit should had been executed.</li>\n</ul>\n"}, {'answer_id': 61428, 'author': 'Joel in Gö', 'author_id': 6091, 'author_profile': 'https://Stackoverflow.com/users/6091', 'pm_score': 1, 'selected': False, 'text': '<p>Never assume that a trivial 2 line method will work. Writing a quick unit test is the only way to prevent the missing null test, misplaced minus sign and/or subtle scoping error from biting you, inevitably when you have even less time to deal with it than now.</p>\n'}, {'answer_id': 61441, 'author': 'Jay Bazuzi', 'author_id': 5314, 'author_profile': 'https://Stackoverflow.com/users/5314', 'pm_score': 3, 'selected': False, 'text': '<p><strong>Some properties of great unit tests:</strong></p>\n\n<ul>\n<li><p>When a test fails, it should be immediately obvious where the problem lies.  If you have to use the debugger to track down the problem, then your tests aren\'t granular enough.  Having exactly one assertion per test helps here.</p></li>\n<li><p>When you refactor, no tests should fail.</p></li>\n<li><p>Tests should run so fast that you never hesitate to run them.</p></li>\n<li><p>All tests should pass always; no non-deterministic results.</p></li>\n<li><p>Unit tests should be well-factored, just like your production code.</p></li>\n</ul>\n\n<p>@Alotor: If you\'re suggesting that a library should only have unit tests at its external API, I disagree.  I want unit tests for each class, including classes that I don\'t expose to external callers.  (However, <a href="https://stackoverflow.com/questions/34571/whats-the-best-way-of-unit-testing-private-methods#52054">if I feel the need to write tests for private methods, then I need to refactor.</a>)</p>\n\n<hr>\n\n<p>EDIT: There was a comment about duplication caused by "one assertion per test".  Specifically, if you have some code to set up a scenario, and then want to make multiple assertions about it, but only have one assertion per test, you might duplication the setup across multiple tests.</p>\n\n<p>I don\'t take that approach.  Instead, I use test fixtures <em>per scenario</em>.  Here\'s a rough example:</p>\n\n<pre><code>[TestFixture]\npublic class StackTests\n{\n    [TestFixture]\n    public class EmptyTests\n    {\n        Stack&lt;int&gt; _stack;\n\n        [TestSetup]\n        public void TestSetup()\n        {\n            _stack = new Stack&lt;int&gt;();\n        }\n\n        [TestMethod]\n        [ExpectedException (typeof(Exception))]\n        public void PopFails()\n        {\n            _stack.Pop();\n        }\n\n        [TestMethod]\n        public void IsEmpty()\n        {\n            Assert(_stack.IsEmpty());\n        }\n    }\n\n    [TestFixture]\n    public class PushedOneTests\n    {\n        Stack&lt;int&gt; _stack;\n\n        [TestSetup]\n        public void TestSetup()\n        {\n            _stack = new Stack&lt;int&gt;();\n            _stack.Push(7);\n        }\n\n        // Tests for one item on the stack...\n    }\n}\n</code></pre>\n'}, {'answer_id': 61458, 'author': 'Haacked', 'author_id': 598, 'author_profile': 'https://Stackoverflow.com/users/598', 'pm_score': 3, 'selected': False, 'text': '<p>Tests should be isolated. One test should not depend on another. Even further, a test should not rely on external systems. In other words, test <em>your</em> code, not the code your code depends on.You can test those interactions as part of your integration or functional tests.</p>\n'}, {'answer_id': 61648, 'author': 'VonC', 'author_id': 6309, 'author_profile': 'https://Stackoverflow.com/users/6309', 'pm_score': 0, 'selected': False, 'text': '<p>Often unit tests are based on mock object or mock data.\nI like to write three kind of unit tests:</p>\n\n<ul>\n<li>"transient" unit tests: they create their own mock objects/data and test their function with it, but destroy everything and leave no trace (like no data in a test database)</li>\n<li>"persistent" unit test: they test functions within your code creating objects/data that will be needed by more advanced function later on for their own unit test (avoiding for those advanced function to recreate every time their own set of mock objects/data)</li>\n<li>"persistent-based" unit tests: unit tests using mock objects/data that are already there (because created in another unit test session) by the persistent unit tests.</li>\n</ul>\n\n<p>The point is to avoid to replay <em>everything</em> in order to be able to test every functions.</p>\n\n<ul>\n<li>I run the third kind very often because all mock objects/data are already there.</li>\n<li>I run the second kind whenever my model change.</li>\n<li>I run the first one to check the very basic functions once in a while, to check to basic regressions.</li>\n</ul>\n'}, {'answer_id': 61667, 'author': 'Techboy', 'author_id': 2699, 'author_profile': 'https://Stackoverflow.com/users/2699', 'pm_score': 0, 'selected': False, 'text': '<p>Think about the 2 types of testing and treat them differently - functional testing and performance testing.</p>\n\n<p>Use different inputs and metrics for each. You may need to use different software for each type of test.</p>\n'}, {'answer_id': 61839, 'author': 'marcospereira', 'author_id': 4600, 'author_profile': 'https://Stackoverflow.com/users/4600', 'pm_score': 2, 'selected': False, 'text': '<p>Jay Fields has a <a href="http://blog.jayfields.com/search/label/Testing%20Refactorings" rel="nofollow noreferrer">lot of good advices</a> about writing unit tests and there is <a href="http://blog.jayfields.com/2008/06/developer-testing-and-importance-of.html" rel="nofollow noreferrer">a post where he summarize the most important advices</a>. There you will read that you should critically think about your context and judge if the advice is worth to you. You get a ton of amazing answers here, but is up to you decide which is best for your context. Try them and just refactoring if it smells bad to you.</p>\n\n<p>Kind Regards</p>\n'}, {'answer_id': 61868, 'author': 'Gishu', 'author_id': 1695, 'author_profile': 'https://Stackoverflow.com/users/1695', 'pm_score': 8, 'selected': True, 'text': '<p>Let me begin by plugging sources - <a href="http://pragprog.com/titles/utj/pragmatic-unit-testing-in-java-with-junit" rel="nofollow noreferrer">Pragmatic Unit Testing in Java with JUnit</a> (There\'s a version with C#-Nunit too.. but I have this one.. its agnostic for the most part. Recommended.)</p>\n\n<p>Good Tests should be <strong>A TRIP</strong> (The acronymn isn\'t sticky enough - I have a printout of the cheatsheet in the book that I had to pull out to make sure I got this right..)</p>\n\n<ul>\n<li><strong>Automatic</strong> : Invoking of tests as well as checking results for PASS/FAIL should be automatic</li>\n<li><strong>Thorough</strong>: Coverage; Although bugs tend to cluster around certain regions in the code, ensure that you test all key paths and scenarios.. Use tools if you must to know untested regions</li>\n<li><strong>Repeatable</strong>: Tests should produce the same results each time.. every time. Tests should not rely on uncontrollable params.</li>\n<li><strong>Independent</strong>: Very important. \n\n<ul>\n<li>Tests should <strong>test only one thing</strong> at a time. Multiple assertions are okay as long as they are all testing one feature/behavior. When a test fails, it should pinpoint the location of the problem.</li>\n<li>Tests <strong>should not rely on each other</strong> - Isolated. No assumptions about order of test execution. Ensure \'clean slate\' before each test by using setup/teardown appropriately</li>\n</ul></li>\n<li><p><strong>Professional</strong>: In the long run you\'ll have as much test code as production (if not more), therefore follow the same standard of good-design for your test code. Well factored methods-classes with intention-revealing names, No duplication, tests with good names, etc. </p></li>\n<li><p>Good tests also run <strong>Fast</strong>. any test that takes over half a second to run.. needs to be worked upon. The longer the test suite takes for a run.. the less frequently it will be run. The more changes the dev will try to sneak between runs.. if anything breaks.. it will take longer to figure out which change was the culprit.</p></li>\n</ul>\n\n<p>Update 2010-08:</p>\n\n<ul>\n<li><strong>Readable</strong> : This can be considered part of Professional - however it can\'t be stressed enough. An acid test would be to find someone who isn\'t part of your team and asking him/her to figure out the behavior under test within a couple of minutes. Tests need to be maintained just like production code - so make it easy to read even if it takes more effort. Tests should be symmetric (follow a pattern) and concise (test one behavior at a time). Use a consistent naming convention (e.g. the TestDox style). Avoid cluttering the test with "incidental details".. become a minimalist.</li>\n</ul>\n\n<p>Apart from these, most of the others are guidelines that cut down on low-benefit work: e.g. \'Don\'t test code that you don\'t own\' (e.g. third-party DLLs). Don\'t go about testing getters and setters. Keep an eye on cost-to-benefit ratio or defect probability.</p>\n'}, {'answer_id': 62198, 'author': 'Peter Evjan', 'author_id': 3397, 'author_profile': 'https://Stackoverflow.com/users/3397', 'pm_score': 3, 'selected': False, 'text': '<p>I like the Right BICEP acronym from the aforementioned <a href="http://www.pragprog.com/titles/utc2/pragmatic-unit-testing-in-c-with-nunit" rel="nofollow noreferrer">Pragmatic Unit Testing</a> book:</p>\n\n<ul>\n<li><strong>Right</strong>: Are the results <strong>right</strong>? </li>\n<li><strong>B</strong>: Are all the <strong>b</strong>oundary conditions correct?</li>\n<li><strong>I</strong>: Can we check <strong>i</strong>nverse relationships?</li>\n<li><strong>C</strong>: Can we <strong>c</strong>ross-check results using other means?</li>\n<li><strong>E</strong>: Can we force <strong>e</strong>rror conditions to happen?</li>\n<li><strong>P</strong>: Are <strong>p</strong>erformance characteristics within bounds?</li>\n</ul>\n\n<p>Personally I feel that you can get pretty far by checking that you get the right results (1+1 should return 2 in a addition function), trying out all the boundary conditions you can think of (such as using two numbers of which the sum is greater than the integer max value in the add function) and forcing error conditions such as network failures.</p>\n'}, {'answer_id': 146551, 'author': 'RoyOsherove', 'author_id': 18426, 'author_profile': 'https://Stackoverflow.com/users/18426', 'pm_score': 3, 'selected': False, 'text': '<p>I covered these principles a while back in <a href="http://msdn.microsoft.com/en-us/magazine/cc163665.aspx" rel="noreferrer">This MSDN Magazine article</a> which I think is important for any developer to read.</p>\n\n<p>The way I define "good" unit tests, is if they posses the following three properties:</p>\n\n<ul>\n<li>They are readable (naming, asserts, variables, length, complexity..)</li>\n<li>They are Maintainable (no logic, not over specified, state-based, refactored..)</li>\n<li>They are trust-worthy (test the right thing, isolated, not integration tests..)</li>\n</ul>\n'}, {'answer_id': 180574, 'author': 'akuhn', 'author_id': 24468, 'author_profile': 'https://Stackoverflow.com/users/24468', 'pm_score': 1, 'selected': False, 'text': '<p>I second the "A TRIP" answer, except that <strong>tests SHOULD rely on each other!!!</strong></p>\n\n<p>Why?</p>\n\n<p>DRY - Dont Repeat Yourself - applies to testing as well! Test dependencies can help to 1) save setup time, 2) save fixture resources, and 3) pinpoint to failures. Of course, only given that your testing framework supports first-class dependencies. Otherwise, I admit, they are bad.</p>\n\n<p>Follow up <a href="http://www.iam.unibe.ch/~scg/Research/JExample/" rel="nofollow noreferrer">http://www.iam.unibe.ch/~scg/Research/JExample/</a> </p>\n'}, {'answer_id': 787088, 'author': 'DanM', 'author_id': 92265, 'author_profile': 'https://Stackoverflow.com/users/92265', 'pm_score': 3, 'selected': False, 'text': "<p><strong>Good tests need to be maintainable.</strong></p>\n\n<p>I haven't quite figured out how to do this for complex environments.</p>\n\n<p>All the textbooks start to come unglued as your code base starts reaching\ninto the hundreds of 1000's or millions of lines of code.</p>\n\n<ul>\n<li>Team interactions explode</li>\n<li>number of test cases explode</li>\n<li>interactions between components explodes.</li>\n<li>time to build all the unittests becomes a significant part of the build time</li>\n<li>an API change can ripple to hundreds of test cases. Even though the production   code change was easy.</li>\n<li>the number of events required to sequence processes into the right state increases   which in turn increases test execution time.</li>\n</ul>\n\n<p>Good architecture can control some of interaction explosion, but inevitably as\nsystems become more complex the automated testing system grows with it.</p>\n\n<p>This is where you start having to deal with trade-offs:</p>\n\n<ul>\n<li>only test external API otherwise refactoring internals results in significant test case rework.</li>\n<li>setup and teardown of each test gets more complicated as an encapsulated subsystem retains more state.</li>\n<li>nightly compilation and automated test execution grows to hours.</li>\n<li>increased compilation and execution times means designers don't or won't run all the tests</li>\n<li>to reduce test execution times you consider sequencing tests to take reduce set up and teardown</li>\n</ul>\n\n<p>You also need to decide:</p>\n\n<p>where do you store test cases in your code base?</p>\n\n<ul>\n<li>how do you document your test cases?</li>\n<li>can test fixtures be re-used to save test case maintenance?</li>\n<li>what happens when a nightly test case execution fails? Who does the triage?</li>\n<li>How do you maintain the mock objects? If you have 20 modules all using their own flavor of a mock logging API, changing the API ripples quickly. Not only do the test cases change but the 20  mock objects change. Those 20 modules were written over several years by many different teams. Its a classic re-use problem.</li>\n<li>individuals and their teams understand the value of automated tests they just don't like how the other team is doing it. :-)</li>\n</ul>\n\n<p>I could go on forever, but my point is that:</p>\n\n<p><strong>Tests need to be maintainable.</strong></p>\n"}, {'answer_id': 831542, 'author': 'womp', 'author_id': 63756, 'author_profile': 'https://Stackoverflow.com/users/63756', 'pm_score': 5, 'selected': False, 'text': '<p>Most of the answers here seem to address unit testing best practices in general (when, where, why and what), rather than actually writing the tests themselves (how).  Since the question seemed pretty specific on the "how" part, I thought I\'d post this, taken from a "brown bag" presentation that I conducted at my company.</p>\n\n<h2><strong>Womp\'s 5 Laws of Writing Tests:</strong></h2>\n\n<hr>\n\n<p><strong>1. Use long, descriptive test method names.</strong></p>\n\n<pre><code>   - Map_DefaultConstructorShouldCreateEmptyGisMap()\n   - ShouldAlwaysDelegateXMLCorrectlyToTheCustomHandlers()\n   - Dog_Object_Should_Eat_Homework_Object_When_Hungry()\n</code></pre>\n\n<p><strong>2. Write your tests in an <a href="http://www.lostechies.com/blogs/jimmy_bogard/archive/2008/07/24/arrange-act-assert-and-bdd-specifications.aspx" rel="nofollow noreferrer">Arrange/Act/Assert style</a>.</strong></p>\n\n<ul>\n<li>While this organizational strategy\nhas been around for a while and\ncalled many things, the introduction\nof the "AAA" acronym recently has\nbeen a great way to get this across. \nMaking all your tests consistent with\nAAA style makes them easy to read and\nmaintain.</li>\n</ul>\n\n<p><strong>3. Always provide a failure message with your Asserts.</strong></p>\n\n<pre><code>Assert.That(x == 2 &amp;&amp; y == 2, "An incorrect number of begin/end element \nprocessing events was raised by the XElementSerializer");\n</code></pre>\n\n<ul>\n<li>A simple yet rewarding practice that makes it obvious in your runner application what has failed.  If you don\'t provide a message, you\'ll usually get something like "Expected true, was false" in your failure output, which makes you have to actually go read the test to find out what\'s wrong.</li>\n</ul>\n\n<p><strong>4. Comment the reason for the test</strong> – what’s the business assumption?</p>\n\n<pre><code>  /// A layer cannot be constructed with a null gisLayer, as every function \n  /// in the Layer class assumes that a valid gisLayer is present.\n  [Test]\n  public void ShouldNotAllowConstructionWithANullGisLayer()\n  {\n  }\n</code></pre>\n\n<ul>\n<li>This may seem obvious, but this\npractice will protect the integrity\nof your tests from people who don\'t\nunderstand the reason behind the test\nin the first place.  I\'ve seen many\ntests get removed or modified that\nwere perfectly fine, simply because\nthe person didn\'t understand the\nassumptions that the test was\nverifying.</li>\n<li>If the test is trivial or the method\nname is sufficiently descriptive, it\ncan be permissible to leave the\ncomment off.</li>\n</ul>\n\n<p><strong>5. Every test must always revert the state of any resource it touches</strong></p>\n\n<ul>\n<li>Use mocks where possible to avoid\ndealing with real resources.</li>\n<li>Cleanup must be done at the test\nlevel.  Tests must not have any\nreliance on order of execution.</li>\n</ul>\n'}, {'answer_id': 3484427, 'author': 'Yack', 'author_id': 118272, 'author_profile': 'https://Stackoverflow.com/users/118272', 'pm_score': 0, 'selected': False, 'text': '<p>I use a consistent test naming convention described by <a href="http://weblogs.asp.net/rosherove/archive/2005/04/03/TestNamingStandards.aspx" rel="nofollow noreferrer">Roy Osherove\'s Unit Test Naming standards</a> Each method in a given test case class has the following naming style MethodUnderTest_Scenario_ExpectedResult.  </p>\n\n<ul>The first test name section is the name of the method in the system under test.</ul>\n\n<ul>Next is the specific scenario that is being tested.</ul>\n\n<ul>Finally is the results of that scenario.</ul>\n\n<p>Each section uses Upper Camel Case and is delimited by a under score.</p>\n\n<p>I have found this useful when I run the test the test are grouped by the name of the method under test. And have a convention allows other developers to understand the test intent.</p>\n\n<p>I also append parameters to the Method name if the method under test have been overloaded.</p>\n'}]
['https://Stackoverflow.com/questions/61400', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3713/']