<p>I am working to integrate unit testing into the development process on the team I work on and there are some sceptics. What are some good ways to convince the sceptical developers on the team of the value of Unit Testing? In my specific case we would be adding Unit Tests as we add functionality or fixed bugs. Unfortunately our code base does not lend itself to easy testing.</p>

[{'answer_id': 67322, 'author': 'pkaeding', 'author_id': 4257, 'author_profile': 'https://Stackoverflow.com/users/4257', 'pm_score': 5, 'selected': False, 'text': '<p>One great thing about unit tests is that they serve as documentation for how your code is meant to behave.  Good tests are kind of like a reference implementation, and teammates can look at them to see how to integrate their code with yours.</p>\n'}, {'answer_id': 67332, 'author': 'Deathbob', 'author_id': 8264, 'author_profile': 'https://Stackoverflow.com/users/8264', 'pm_score': 1, 'selected': False, 'text': '<p>The whole point of unit testing is to make testing easy.  It\'s automated.  "make test" and you\'re done.  If one of the problems you face is difficult to test code, that\'s the best reason of all to use unit testing.  </p>\n'}, {'answer_id': 67338, 'author': 'Ed Guiness', 'author_id': 4200, 'author_profile': 'https://Stackoverflow.com/users/4200', 'pm_score': 7, 'selected': False, 'text': '<p>Best way to convince... find a bug, write a unit test for it, fix the bug.  </p>\n\n<p>That particular bug is unlikely to ever appear again, and you can prove it with your test.</p>\n\n<p>If you do this enough, others will catch on quickly.  </p>\n'}, {'answer_id': 67356, 'author': 'Craig H', 'author_id': 2328, 'author_profile': 'https://Stackoverflow.com/users/2328', 'pm_score': 0, 'selected': False, 'text': '<p>Who are you trying to convince?  Engineers or manager?  If you are trying to convince your engineer co-workers I think your best bet is to appeal to their desire to make a high quality piece of software.  There are numerous studies that show it finds bugs, and if they care about doing a good job, that should be enough for them.</p>\n\n<p>If you are trying to convince management, you will most likely have to do some kind of cost/benefit reasoning saying that the cost of the defects that will be undetected is greater than the cost of writing the tests.  Be sure to include intagable costs too, such as loss of customer confidence, etc.</p>\n'}, {'answer_id': 67357, 'author': 'Tom Martin', 'author_id': 5303, 'author_profile': 'https://Stackoverflow.com/users/5303', 'pm_score': 4, 'selected': False, 'text': '<p>A major part of test-driven development that is often glossed over is the writing of testable code.  It seems like some kind of a compromise at first, but you\'ll discover that testable code is also ultimately modular, maintainable and readable.\nIf you still need help convincing people <a href="http://www.masukomi.org/talks/unit_testing_talk_2/index.xul?data=slide_data.txt#page1" rel="noreferrer">this</a> is a nice simple presentation about the advantages of unit testing.</p>\n'}, {'answer_id': 67365, 'author': 'Garth Gilmour', 'author_id': 2635682, 'author_profile': 'https://Stackoverflow.com/users/2635682', 'pm_score': 2, 'selected': False, 'text': "<p>If you are using NUnit one simple but effective demo is to run NUnit's own test suite(s) in front of them. Seeing a real test suite giving a codebase a workout is worth a thousand words...</p>\n"}, {'answer_id': 67385, 'author': 'Ray Hayes', 'author_id': 7093, 'author_profile': 'https://Stackoverflow.com/users/7093', 'pm_score': 1, 'selected': False, 'text': "<p>When you manually test software, you normally have a small set of tests/actions that you use.  Eventually you'll automatically morph your input data or actions so that you navigate yourself around known issues.  Unit tests should be there to remind you that things do not work correctly.</p>\n\n<p>I recommend writing tests before code, adding new tests/data to evolve the functionality of the main code!</p>\n"}, {'answer_id': 67392, 'author': 'Fredrik', 'author_id': 9191, 'author_profile': 'https://Stackoverflow.com/users/9191', 'pm_score': 1, 'selected': False, 'text': '<p>As a physics student i am very driven to actually <em>prove</em> that my code works as it is supposed to. You could either prove this logically, which increases in difficulty drastically as implementation gets more complex, or you can make an (as close as possible) empirical proof of function through good testing.</p>\n\n<p>If you don\'t provide logical proof of function, you have to test. The only alternative is to say "I think the code works...."</p>\n'}, {'answer_id': 67430, 'author': 'Eric Z Beard', 'author_id': 1219, 'author_profile': 'https://Stackoverflow.com/users/1219', 'pm_score': 4, 'selected': False, 'text': "<p>If your existing code base doesn't lend itself to unit testing, and it's already in production, you might create more problems than you solve by trying to refactor all of your code so that it is unit-testable.</p>\n\n<p>You may be better off putting efforts towards improving your integration testing instead.  There's lots of code out there that's just simpler to write without a unit test, and if a QA can validate the functionality against a requirements document, then you're done.  Ship it.</p>\n\n<p>The classic example of this in my mind is a SqlDataReader embedded in an ASPX page linked to a GridView.  The code is all in the ASPX file.  The SQL is in a stored procedure.  What do you unit test?  If the page does what it's supposed to do, should you really redesign it into several layers so you have something to automate?</p>\n"}, {'answer_id': 67432, 'author': 'Alexandre Brasil', 'author_id': 8841, 'author_profile': 'https://Stackoverflow.com/users/8841', 'pm_score': 3, 'selected': False, 'text': '<p>One of the best things about unit testing is that your code will become easier to test as you do it. Preexisting code created without tests is always a challenge because since they weren\'t meant to be unit-tested, it\'s not rare to have a high level of coupling between classes, hard-to-configure objects inside your class - like an e-mail sending service reference - and so on. But don\'t let this bring you down! You\'ll see that your overall code design will become better as you start to write unit-tests, and the more you test, the more confident you\'ll become on making even more changes to it without fear of breaking you application or introducing bugs.</p>\n\n<p>There are several reasons to unit-test your code, but as time progresses, you\'ll find out that the time you save on testing is one of the best reasons to do it. In a system I\'ve just delivered, I insisted on doing automated unit-testing in spite of the claims that I\'d spend way more time doing the tests than I would by testing the system manually. With all my unit tests done, I run more than 400 test cases in less than 10 minutes, and every time I had to do a small change in the code, all it took me to be sure the code was still working without bugs was ten minutes. Can you imagine the time one would spend to run those 400+ test cases by hand?</p>\n\n<p>When it comes to automated testing - be it unit testing or acceptance testing - everyone thinks it\'s a wasted effort to code what you can do manually, and sometimes it\'s true - if you plan to run your tests only once. The best part of automated testing is that you can run them several times without effort, and after the second or third run, the time and effort you\'ve <em>wasted</em> is already paid for.</p>\n\n<p>One last piece of advice would be to not only unit test your code, but start doing test first (see <a href="http://en.wikipedia.org/wiki/Test-driven_development" rel="noreferrer">TDD</a> and <a href="http://en.wikipedia.org/wiki/Behavior_driven_development" rel="noreferrer">BDD</a> for more)</p>\n'}, {'answer_id': 67436, 'author': 'killdash10', 'author_id': 7621, 'author_profile': 'https://Stackoverflow.com/users/7621', 'pm_score': 3, 'selected': False, 'text': "<p>Unit tests are also especially useful when it comes to refactoring or re-writing a piece a code.  If you have good unit tests coverage, you can refactor with confidence.  Without unit tests, it is often hard to ensure the you didn't break anything.</p>\n"}, {'answer_id': 67440, 'author': 'Max Rible Kaehn', 'author_id': 2512583, 'author_profile': 'https://Stackoverflow.com/users/2512583', 'pm_score': 2, 'selected': False, 'text': "<p>Unit testing helps a lot in projects that are larger than any one developer can hold in their head.  They allow you to run the unit test suite before checkin and discover if you broke something.  This cuts down a <em>lot</em> on instances of having to sit and twiddle your thumbs while waiting for someone else to fix a bug they checked in, or going to the hassle of reverting their change so you can get some work done.  It's also immensely valuable in refactoring, so you can be sure that the refactored code passes all the tests that the original code did.</p>\n"}, {'answer_id': 67442, 'author': 'Matt', 'author_id': 10035, 'author_profile': 'https://Stackoverflow.com/users/10035', 'pm_score': 3, 'selected': False, 'text': "<p>Unit Testing is definitely worth the effort.  Unfortunately you've chosen a difficult (but unfortunately common) scenario into which to implement it.</p>\n\n<p>The best benefit from unit testing you'll get is when using it from the ground up - on a few, select, small projects I've been fortunate enough to write my unit tests before implementing my classes (the interface was already complete at this point).  With proper unit tests, you will find and fix bugs in your classes while they're still in their infancy and not anywhere near the complex system that they'll undoubtedly become integrated in in the future.</p>\n\n<p>If your software is solidly object oriented, you should be able to add unit testing at the class level without too much effort.  If you aren't that fortunate, you should still try to incorporate unit testing wherever you can.  Make sure when you add new functionality the new pieces are well defined with clear interfaces and you'll find unit testing makes your life much easier.</p>\n"}, {'answer_id': 67500, 'author': 'reefnet_alex', 'author_id': 2745, 'author_profile': 'https://Stackoverflow.com/users/2745', 'pm_score': 10, 'selected': True, 'text': '<p>Every day in our office there is an exchange which goes something like this:</p>\n\n<blockquote>\n  <p>"Man, I just love unit tests, I\'ve just been able to make a bunch of changes to the way something works, and then was able to confirm I hadn\'t broken anything by running the test over it again..."</p>\n</blockquote>\n\n<p>The details change daily, but the sentiment doesn\'t. Unit tests and test-driven development (TDD) have so many hidden and personal benefits as well as the obvious ones that you just can\'t really explain to somebody until they\'re doing it themselves. </p>\n\n<p>But, ignoring that, here\'s my attempt!</p>\n\n<ol>\n<li><p>Unit Tests allows you to make big changes to code quickly. You know it works now because you\'ve run the tests, when you make the changes you need to make, you need to get the tests working again. This saves hours. </p></li>\n<li><p>TDD helps you to realise when to stop coding. Your tests give you confidence that you\'ve done enough for now and can stop tweaking and move on to the next thing.</p></li>\n<li><p>The tests and the code work together to achieve better code. Your code could be bad / buggy. Your TEST could be bad / buggy. In TDD you are banking on the chances of <strong>both</strong> being bad / buggy being low. Often it\'s the test that needs fixing but that\'s still a good outcome. </p></li>\n<li><p>TDD helps with coding constipation. When faced with a large and daunting piece of work ahead writing the tests will get you moving quickly.</p></li>\n<li><p>Unit Tests help you really understand the design of the code you are working on. Instead of writing code to do something, you are starting by outlining all the conditions you are subjecting the code to and what outputs you\'d expect from that. </p></li>\n<li><p>Unit Tests give you instant visual feedback, we all like the feeling of all those green lights when we\'ve done. It\'s very satisfying. It\'s also much easier to pick up where you left off after an interruption because you can see where you got to - that next red light that needs fixing. </p></li>\n<li><p>Contrary to popular belief unit testing does not mean writing twice as much code, or coding slower. It\'s faster and more robust than coding without tests once you\'ve got the hang of it. Test code itself is usually relatively trivial and doesn\'t add a big overhead to what you\'re doing. This is one you\'ll only believe when you\'re doing it :)</p></li>\n<li><p>I think it was Fowler who said: "Imperfect tests, run frequently, are much better than perfect tests that are never written at all". I interpret this as giving me permission to write tests where I think they\'ll be most useful even if the rest of my code coverage is woefully incomplete.</p></li>\n<li><p>Good unit tests can help document and define what something is supposed to do</p></li>\n<li><p>Unit tests help with code re-use. Migrate both your code <strong>and</strong> your tests to your new project. Tweak the code till the tests run again.</p></li>\n</ol>\n\n<p>A lot of work I\'m involved with doesn\'t Unit Test well (web application user interactions etc.), but even so we\'re all test infected in this shop, and happiest when we\'ve got our tests tied down. I can\'t recommend the approach highly enough. </p>\n'}, {'answer_id': 67524, 'author': 'Raz', 'author_id': 5661, 'author_profile': 'https://Stackoverflow.com/users/5661', 'pm_score': 1, 'selected': False, 'text': '<p>One of the benefits of unit testing is predictability. </p>\n\n<p>Before unit testing I could have predicted to a great degree of accuracy how long it would take to code something, but not how how much time I would need to debug it. </p>\n\n<p>These days, since I can plan what tests I am going to write, I know how long coding is going to take, and at the end of coding, the system is already debugged! This brings predictability to the development process, which remove a lot of the pressure but still retains all the joy!!. </p>\n'}, {'answer_id': 67555, 'author': 'Jonathan Webb', 'author_id': 1518, 'author_profile': 'https://Stackoverflow.com/users/1518', 'pm_score': 5, 'selected': False, 'text': "<p>Unit-testing is well worth the initial investment. Since starting to use unit-testing a couple of years ago, I've found some real benefits:</p>\n\n<ul>\n<li><strong>regression testing</strong> removes the fear of\nmaking changes to code (there's nothing\nlike the warm glow of seeing code\nwork or explode every time a change is\nmade)</li>\n<li><strong>executable code examples</strong> for\nother team members (and yourself in\nsix months time..)</li>\n<li><strong><em>merciless</em> refactoring</strong> - this is incredibly rewarding, try it!</li>\n</ul>\n\n<p>Code snippets can be a great help in reducing the overhead of creating tests. It isn't difficult to create snippets that enable the creation of a class outline and an associated unit-test fixture in seconds.</p>\n"}, {'answer_id': 67611, 'author': 'cranley', 'author_id': 10308, 'author_profile': 'https://Stackoverflow.com/users/10308', 'pm_score': 3, 'selected': False, 'text': '<p>In short - yes.  They are worth every ounce of effort... to a point.  Tests are, at the end of the day, still code, and much like typical code growth, your tests will eventually need to be refactored in order to be maintainable and sustainable.  There\'s a tonne of GOTCHAS! when it comes to unit testing, but man oh man oh man, nothing, and I mean NOTHING empowers a developer to make changes more confidently than a rich set of unit tests.</p>\n\n<p>I\'m working on a project right now.... it\'s somewhat TDD, and we have the majority of our business rules encapuslated as tests... we have about 500 or so unit tests right now.  This past iteration I had to revamp our datasource and how our desktop application interfaces with that datasource.  Took me a couple days, the whole time I just kept running unit tests to see what I broke and fixed it.  Make a change; Build and run your tests; fix what you broke.  Wash, Rinse, Repeat as necessary.  What would have traditionally taken days of QA and boat loads of stress was instead a short and enjoyable experience.</p>\n\n<p>Prep up front, a little bit of extra effort, and it pays 10-fold later on when you have to start dicking around with core features/functionality.  </p>\n\n<p>I bought this book - it\'s a Bible of xUnit Testing knowledge - tis probably one of the most referenced books on my shelf, and I consult it daily:  <a href="https://rads.stackoverflow.com/amzn/click/com/0131495054" rel="noreferrer" rel="nofollow noreferrer" title="xUnit Test Patterns">link text</a></p>\n'}, {'answer_id': 67951, 'author': 'Keith Nicholas', 'author_id': 10431, 'author_profile': 'https://Stackoverflow.com/users/10431', 'pm_score': 5, 'selected': False, 'text': "<p>You should test as little as possible!</p>\n\n<p>meaning, you should write just enough unit tests to reveal intent.  This often gets glossed over.  Unit testing costs you.  If you make changes and you have to change tests you will be less agile.   Keep unit tests short and sweet.    Then they have a lot of value.</p>\n\n<p>Too often I see lots of tests that will never break, are big and clumsy and don't offer a lot of value, they just end up slowing you down.</p>\n"}, {'answer_id': 67972, 'author': 'Shinwari', 'author_id': 10513, 'author_profile': 'https://Stackoverflow.com/users/10513', 'pm_score': 2, 'selected': False, 'text': '<p>With unit test suite one can make changes to code while leaving rest of the features intact. Its a great advantage. Do you use Unit test sutie and regression test suite when ever you finish coding new feature.</p>\n'}, {'answer_id': 68019, 'author': 'Vinny Carpenter', 'author_id': 10511, 'author_profile': 'https://Stackoverflow.com/users/10511', 'pm_score': 2, 'selected': False, 'text': "<p>Yes - Unit Testing is definitely worth the effort but you should know it's not a silver bullet.  Unit Testing is work and you will have to work to keep the test updated and relevant as code changes but the value offered is worth the effort you have to put in.  The ability to refactor with impunity is a huge benefit as you can always validate functionality by running your tests after any change code.  The trick is to not get too hung up on exactly the unit-of-work you're testing or how you are scaffolding test requirements and when a unit-test is really a functional test, etc.  People will argue about this stuff for hours on end and the reality is that any testing you do as your write code is better than not doing it.  The other axiom is about quality and not quantity - I have seen code-bases with 1000's of test that are essentially meaningless as the rest don't really test anything useful or anything domain specific like business rules, etc of the particular domain.  I've also seen codebases with 30% code coverage but the tests were relevant, meaningful and really awesome as they tested the core functionality of the code it was written for and expressed how the code should be used. </p>\n\n<p>One of my favorite tricks when exploring new frameworks or codebases is to write unit-tests for 'it' to discover how things work.  It's a great way to learn more about something new instead of reading a dry doc :)  </p>\n"}, {'answer_id': 68290, 'author': 'dlanod', 'author_id': 10247, 'author_profile': 'https://Stackoverflow.com/users/10247', 'pm_score': 2, 'selected': False, 'text': '<p>I recently went through the exact same experience in my workplace and found most of them knew the theoretical benefits but had to be sold on the benefits to them specifically, so here were the points I used (successfully):</p>\n\n<ul>\n<li>They save time when performing negative testing, where you handle unexpected inputs (null pointers, out of bounds values, etc), as you can do all these in a single process.</li>\n<li>They provide immediate feedback at compile time regarding the standard of the changes.  </li>\n<li>They are useful for testing internal data representations that may not be exposed during normal runtime.</li>\n</ul>\n\n<p>and the big one...</p>\n\n<ul>\n<li>You might not need unit testing, but when someone else comes in and modifies the code without a full understanding it can catch a lot of the silly mistakes they might make.</li>\n</ul>\n'}, {'answer_id': 68360, 'author': 'Keith Elder', 'author_id': 10624, 'author_profile': 'https://Stackoverflow.com/users/10624', 'pm_score': 3, 'selected': False, 'text': '<p>When you said, "our code base does not lend itself to easy testing" is the first sign of a code smell.  Writing Unit Tests means you typically write code differently in order to make the code more testable.  This is a good thing in my opinion as what I\'ve seen over the years in writing code that I had to write tests for, it forced me to put forth a better design.  </p>\n'}, {'answer_id': 68567, 'author': 'Curro', 'author_id': 10688, 'author_profile': 'https://Stackoverflow.com/users/10688', 'pm_score': 4, 'selected': False, 'text': "<p>For years, I've tried to convince people that they needed to write unit test for their code. Whether they wrote the tests first (as in TDD) or after they coded the functionality, I always tried to explain them all the benefits of having unit tests for code. Hardly anyone disagreed with me. You cannot disagree with something that is obvious, and any smart person will see the benefits of unit test and TDD.</p>\n\n<p>The problem with unit testing is that it requires a behavioral change, and it is very hard to change people's behavior. With words, you will get a lot of people to agree with you, but you won't see many changes in the way they do things.</p>\n\n<p>You have to convince people by doing. Your personal success will atract more people than all the arguments you may have. If they see you are not just talking about unit test or TDD, but you are doing what you preach, and you are successful, people will try to imitate you. </p>\n\n<p>You should also take on a lead role because no one writes unit test right the first time, so you may need to coach them on how to do it, show them the way, and the tools available to them. Help them while they write their first tests, review the tests they write on their own, and show them the tricks, idioms and patterns you've learned through your own experiences. After a while, they will start seeing the benefits on their own, and they will change their behavior to incorporate unit tests or TDD into their toolbox.</p>\n\n<p>Changes won't happen over night, but with a little of patience, you may achieve your goal.</p>\n"}, {'answer_id': 69263, 'author': 'benzado', 'author_id': 10947, 'author_profile': 'https://Stackoverflow.com/users/10947', 'pm_score': 9, 'selected': False, 'text': '<p><strong>Unit testing is a lot like going to the gym.</strong>  You know it is good for you, all the arguments make sense, so you start working out.  There\'s an initial rush, which is great, but after a few days you start to wonder if it is worth the trouble.  You\'re taking an hour out of your day to change your clothes and run on a hamster wheel and you\'re not sure you\'re really gaining anything other than sore legs and arms.</p>\n\n<p>Then, after maybe one or two weeks, just as the soreness is going away, a Big Deadline begins approaching.  You need to spend every waking hour trying to get "useful" work done, so you cut out extraneous stuff, like going to the gym.  You fall out of the habit, and by the time Big Deadline is over, you\'re back to square one.  If you manage to make it back to the gym at all, you feel just as sore as you were the first time you went.</p>\n\n<p>You do some reading, to see if you\'re doing something wrong.  You begin feel a little bit of irrational spite toward all the fit, happy people extolling the virtues of exercise.  You realize that you don\'t have a lot in common.  They don\'t have to drive 15 minutes out of the way to go to the gym; there is one in their building.  They don\'t have to argue with anybody about the benefits of exercise; it is just something everybody does and accepts as important.  When a Big Deadline approaches, they aren\'t told that exercise is unnecessary any more than your boss would ask you to stop eating.</p>\n\n<p><strong>So, to answer your question, Unit Testing is usually worth the effort, but the amount of effort required isn\'t going to be the same for everybody.</strong>  Unit Testing may require an enormous amount of effort if you are dealing with spaghetti code base in a company that doesn\'t <em>actually</em> value code quality.  (A lot of managers will sing Unit Testing\'s praises, but that doesn\'t mean they will stick up for it when it matters.)</p>\n\n<p>If you are trying to introduce Unit Testing into your work and are not seeing all the sunshine and rainbows that you have been led to expect, don\'t blame yourself.  You might need to find a new job to really make Unit Testing work for you.</p>\n'}, {'answer_id': 69544, 'author': 'Jon Cahill', 'author_id': 10830, 'author_profile': 'https://Stackoverflow.com/users/10830', 'pm_score': 3, 'selected': False, 'text': "<p>Occasionally either myself or one of my co-workers will spend a couple of hours getting to the bottom of slightly obscure bug and once the cause of the bug is found 90% of the time that code isn't unit tested.  The unit test doesn't exist because the dev is cutting corners to save time, but then looses this and more debugging.</p>\n\n<p>Taking the small amount of time to write a unit test can save hours of future debugging.</p>\n"}, {'answer_id': 69961, 'author': 'Bert F', 'author_id': 11296, 'author_profile': 'https://Stackoverflow.com/users/11296', 'pm_score': 6, 'selected': False, 'text': '<blockquote>\n  <p>thetalkingwalnut asks:</p>\n  \n  <blockquote>\n    <p>What are some good ways to convince the skeptical developers on the team of the value of Unit Testing?</p>\n  </blockquote>\n</blockquote>\n\n<p>Everyone here is going to pile on lots of reasons out of the blue why unit testing is good. However, I find that often the best way to convince someone of something is to <em>listen</em> to their argument and address it point by point. If you listen and help them verbalize their concerns, you can address each one and perhaps convert them to your point of view (or at the very least, leave them without a leg to stand on). <em>Who knows? Perhaps they will convince you why unit tests aren\'t appropriate for your situation.</em> Not likely, but possible.  Perhaps if you post their arguments against unit tests, we can help identify the counterarguments.</p>\n\n<p>It\'s important to listen to and understand both sides of the argument. If you try to adopt unit tests too zealously without regard to people\'s concerns, you\'ll end up with a religious war (and probably really worthless unit tests). If you adopt it slowly and start by applying it where you will see the most benefit for the least cost, you might be able to demonstrate the value of unit tests and have a better chance of convincing people. I realize this isn\'t as easy as it sounds - it usually requires some time and careful metrics to craft a convincing argument.</p>\n\n<p>Unit tests are a tool, like any other, and should be applied in such a way that the benefits (catching bugs) outweigh the costs (the effort writing them). Don\'t use them if/where they don\'t make sense and remember that they are only part of your arsenal of tools (e.g. inspections, assertions, code analyzers, formal methods, etc). What I tell my developers is this:</p>\n\n<ol>\n<li><p>They can skip writing a test for a method if they have a good argument why it isn\'t necessary (e.g. too simple to be worth it or too difficult to be worth it) and how the method will be otherwise verified (e.g. inspection, assertions, formal methods, interactive/integration tests). They need to consider that some verifications like inspections and formal proofs are done at a point in time and then need to be repeated every time the production code changes, whereas unit tests and assertions can be used as regression tests (written once and executed repeatedly thereafter).  Sometimes I agree with them, but more often I will debate about whether a method is really too simple or too difficult to unit test.</p>\n\n<ul>\n<li><p>If a developer argues that a method seems too simple to fail, isn\'t it worth taking the 60 seconds necessary to write up a simple 5-line unit test for it? These 5 lines of code will run every night (you do nightly builds, right?) for the next year or more and will be worth the effort if even just once it happens to catch a problem that may have taken 15 minutes or longer to identify and debug. Besides, writing the easy unit tests drives up the count of unit tests, which makes the developer look good.</p></li>\n<li><p>On the other hand, if a developer argues that a method seems too difficult to unit test (not worth the significant effort required), perhaps that is a good indication that the method needs to be divided up or refactored to test the easy parts. Usually, these are methods that rely on unusual resources like singletons, the current time, or external resources like a database result set. These methods usually need to be refactored into a method that gets the resource (e.g. calls getTime()) and a method that takes the resource as a argument (e.g. takes the timestamp as a parameter). I let them skip testing the method that retrieves the resource and they instead write a unit test for the method that now takes the resource as a argument. Usually, this makes writing the unit test much simpler and therefore worthwhile to write.</p></li>\n</ul></li>\n<li><p>The developer needs to draw a "line in the sand" in how comprehensive their unit tests should be. Later in development, whenever we find a bug, they should determine if more comprehensive unit tests would have caught the problem. If so and if such bugs crop up repeatedly, they need to move the "line" toward writing more comprehensive unit tests in the future (starting with adding or expanding the unit test for the current bug). They need to find the right balance.</p></li>\n</ol>\n\n<p>Its important to realize the unit tests are not a silver bullet and there <em>is</em> such a thing as too much unit testing. At my workplace, whenever we do a lessons learned, I inevitably hear "we need to write more unit tests". Management nods in agreement because its been banged into their heads that "unit tests" == "good".</p>\n\n<p>However, we need to understand the impact of "more unit tests". A developer can only write ~N lines of code a week and you need to figure out what percentage of that code should be unit test code vs production code. A lax workplace might have 10% of the code as unit tests and 90% of the code as production code, resulting in product with a lot of (albeit very buggy) features (think MS Word). On the other hand, a strict shop with 90% unit tests and 10% production code will have a rock solid product with very few features (think "vi"). You may never hear reports about the latter product crashing, but that likely has as much to do with the product not selling very well as much as it has to do with the quality of the code.</p>\n\n<p>Worse yet, perhaps the only certainty in software development is that "change is inevitable". Assume the strict shop (90% unit tests/10% production code) creates a product that has exactly 2 features (assuming 5% of production code == 1 feature). If the customer comes along and changes 1 of the features, then that change trashes 50% of the code (45% of unit tests and 5% of the production code). The lax shop (10% unit tests/90% production code) has a product with 18 features, none of which work very well. Their customer completely revamps the requirements for 4 of their features. Even though the change is 4 times as large, only half as much of the code base gets trashed (~25% = ~4.4% unit tests + 20% of production code).</p>\n\n<p>My point is that you have to communicate that you understand that balance between too little and too much unit testing - essentially that you\'ve thought through both sides of the issue. If you can convince your peers and/or your management of that, you gain credibility and perhaps have a better chance of winning them over.</p>\n'}, {'answer_id': 107137, 'author': 'Andy Lester', 'author_id': 8454, 'author_profile': 'https://Stackoverflow.com/users/8454', 'pm_score': 1, 'selected': False, 'text': '<p>Make the first things you test not related to unit testing.  I work mostly in Perl, so these are Perl-specific examples, but you can adapt.</p>\n\n<ul>\n<li><p>Does every module load and compile correctly?  In Perl, this is a matter of creating a Foo.t for each Foo.pm in the code base that does:</p>\n\n<pre><code>use_ok( \'Foo\' );\n</code></pre></li>\n<li><p>Is all the POD (Plain Ol\' Documentation) formatted properly?  Use Test::Pod to validate the validity of the formatting of all the POD in all the files.</p></li>\n</ul>\n\n<p>You may not think these are big things, and they\'re not, but I can guarantee you will catch some slop.  When these tests run once an hour, and it catches someone\'s premature commit, you\'ll have people say "Hey, that\'s pretty cool."</p>\n'}, {'answer_id': 530648, 'author': 'John MacIntyre', 'author_id': 29043, 'author_profile': 'https://Stackoverflow.com/users/29043', 'pm_score': 5, 'selected': False, 'text': "<p>I didn't see this in any of the other answers, but one thing I noticed is that <strong>I could debug so much faster</strong>.  You don't need to drill down through your app with just the right sequence of steps to get to the code your fixing, only to find you've made a boolean error and need to do it all again.  With a unit test, you can just step directly into the code you're debugging.</p>\n"}, {'answer_id': 530724, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': -1, 'selected': False, 'text': "<p>Unit testing works for QA guys or your managers, not for you; so it's definitely not worth it.</p>\n\n<p>You should focus on writing correct code (whatever it means), not test cases. Let other guys worry about those.</p>\n"}, {'answer_id': 1011995, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>Unit testing help you to release software with fewer bugs while reducing overall development costs. You can click the link to read more about the <a href="http://www.typemock.com/benefits_of_unit_testing_with_typemock.php" rel="nofollow noreferrer">benefits of unit testing</a></p>\n'}, {'answer_id': 1097441, 'author': 'Ronnie', 'author_id': 44169, 'author_profile': 'https://Stackoverflow.com/users/44169', 'pm_score': 5, 'selected': False, 'text': '<p>I have toyed with unit testing a number of times, and I am still to be convinced that it is worth the effort given my situation. </p>\n\n<p>I develop websites, where much of the logic involves creating, retrieving or updating data in the database. When I have tried to "mock" the database for unit testing purposes, it has got very messy and seemed a bit pointless.</p>\n\n<p>When I have written unit tests around business logic, it has never really helped me in the long run. Because I largely work on projects alone, I tend to know intuitively which areas of code may be affected by something I am working on, and I test these areas manually. I want to deliver a solution to my client as quickly as possible, and unit testing often seems a waste of time. I list manual tests and walk through them myself, ticking them off as I go.</p>\n\n<p>I can see that it may be beneficial when a team of developers are working on a project and updating each other\'s code, but even then I think that if the developers are of a high quality, good communication and well-written code should often be enough.</p>\n'}, {'answer_id': 1154304, 'author': 'mic.sca', 'author_id': 117126, 'author_profile': 'https://Stackoverflow.com/users/117126', 'pm_score': 3, 'selected': False, 'text': "<p>I'm working as a maintenance-engineer of a poorly documented,  awful and big code base. I wish the people who wrote the code had written the unit tests for it.<br>\nEach time I make a change and update the production code I'm scared that I might introduce a bug for not having considered some condition.<br>\nIf they wrote the test making changes to the code base would be  easier and faster.(at the same time the code base would be in a better state)..</p>\n\n<p>I think unit tests prove a lot useful when writing api or frameworks that have to last for many years and to be used/modified/evolved by people other than the original coders.</p>\n"}, {'answer_id': 1154414, 'author': 'Kaz Dragon', 'author_id': 24913, 'author_profile': 'https://Stackoverflow.com/users/24913', 'pm_score': 2, 'selected': False, 'text': '<p>I discovered TDD a couple of years ago, and have since written all my pet projects using it.  I have estimated that it takes roughly the same time to TDD a project as it takes to cowboy it together, but I have such increased confidence in the end product that I can\'t help a feeling of accomplishment.</p>\n\n<p>I also feel that it improves my design style (much more interface-oriented in case I need to mock things together) and, as the green post at the top writes, it helps with "coding constipation": when you don\'t know what to write next, or you have a daunting task in front of you, you can write small.</p>\n\n<p>Finally, I find that by far the most useful application of TDD is in the debugging, if only because you\'ve already developed an interrogatory framework with which you can prod the project into producing the bug in a repeatable fashion.</p>\n'}, {'answer_id': 1300595, 'author': 'Chris Gill', 'author_id': 159226, 'author_profile': 'https://Stackoverflow.com/users/159226', 'pm_score': 4, 'selected': False, 'text': '<p>[I have a point to make that I cant see above]</p>\n\n<p>"Everyone unit tests, they don\'t necessarily realise it - FACT"</p>\n\n<p>Think about it, you write a function to maybe parse a string and remove new line characters. As a newbie developer you either run a few cases through it from the command line by implementing it in Main() or you whack together a visual front end with a button, tie up your function to a couple of text boxes and a button and see what happens.</p>\n\n<p>That is unit testing - basic and badly put together but you test the piece of code for a few cases. </p>\n\n<p>You write something more complex. It throws errors when you throw a few cases through (unit testing) and you debug into the code and trace though. You look at values as you go through and decide if they are right or wrong. This is unit testing to some degree. </p>\n\n<p>Unit testing here is really taking that behaviour, formalising it into a structured pattern and saving it so that you can easily re-run those tests. If you write a "proper" unit test case rather than manually testing, it takes the same amount of time, or maybe less as you get experienced, and you have it available to repeat again and again</p>\n'}, {'answer_id': 2878822, 'author': 'BigTiger', 'author_id': 346652, 'author_profile': 'https://Stackoverflow.com/users/346652', 'pm_score': 3, 'selected': False, 'text': '<p>I do not know. A lot of places do not do unit test, but the quality of the code is good. Microsoft does unit test, but Bill Gates gave a blue screen at his presentation.</p>\n'}, {'answer_id': 3833608, 'author': 'crowne', 'author_id': 97745, 'author_profile': 'https://Stackoverflow.com/users/97745', 'pm_score': 1, 'selected': False, 'text': "<p>Just today, I had to change a class for which a unit test has been written previously.<br>\nThe test itself was well written and included test scenarios that I hadn't even thought about.<br>\nLuckily all of the tests passed, and my change was quickly verified and put into the test environment with confidence.  </p>\n"}, {'answer_id': 3833651, 'author': 'Tom W', 'author_id': 313414, 'author_profile': 'https://Stackoverflow.com/users/313414', 'pm_score': 0, 'selected': False, 'text': '<p>This is very .Net-centric, but has anybody tried <strong>Pex</strong>?</p>\n\n<p>I was extremely sceptical until I tried it - and wow, what a performance. Before I thought "I\'m not going to be convinced by this concept until I understand what it\'s actually <em>doing</em> to benefit me". It took a single run for me to change my mind and say "I don\'t <em>care</em> how you know there\'s the risk of a fatal exception there, but there <em>is</em> and now I know I have to deal with it"</p>\n\n<p>Perhaps the only downside to this behaviour is that it will flag up <em>everything</em> and give you a six month backlog. But, if you had code debt, you always had code debt, you just didn\'t know it. Telling a PM there are a potential two hundred thousand points of failure when before you were aware of a few dozen is a nasty prospect, which means it is vital that the concept is <em>explained first.</em></p>\n'}, {'answer_id': 3835695, 'author': 'Cedric Beust', 'author_id': 162410, 'author_profile': 'https://Stackoverflow.com/users/162410', 'pm_score': 2, 'selected': False, 'text': "<p>The one thing to keep in mind about unit testing is that it's a comfort for the developer.</p>\n\n<p>In contrast, functional tests are for the users: whenever you add a functional test, you are testing something that the user will see. When you add a unit test, you are just making your life easier as a developer. It's a little bit of a luxury in that respect.</p>\n\n<p>Keep this dichotomy in mind when you have to make a choice between writing a unit or a functional test.</p>\n"}, {'answer_id': 3840617, 'author': 'Toran Billups', 'author_id': 2701, 'author_profile': 'https://Stackoverflow.com/users/2701', 'pm_score': 3, 'selected': False, 'text': '<p>I wrote a very large blog post about the topic.  I\'ve found that unit testing alone isn\'t worth the work and usually gets cut when deadlines get closer.</p>\n\n<p>Instead of talking about unit testing from the "test-after" verification point of view, we should look at the true value found when you set out to write a spec/test/idea before the implementation.</p>\n\n<p>This simple idea has changed the way I write software and I wouldn\'t go back to the "old" way.</p>\n\n<p><a href="http://toranbillups.com/blog/archive/2010/04/22/How-test-first-development-changed-my-life/" rel="nofollow">How test first development changed my life</a></p>\n'}, {'answer_id': 4207111, 'author': 'Liorp', 'author_id': 511074, 'author_profile': 'https://Stackoverflow.com/users/511074', 'pm_score': 2, 'selected': False, 'text': '<p>From my experience, unit tests and integration tests are a "MUST HAVE" in complex software environments.</p>\n\n<p>In order to convince the developers in your team to write unit tests you may want to consider integrating unit test regression analysis in your development environment (for example, in your daily build process).</p>\n\n<p>Once developers know that if a unit test fails they don\'t have to spend so much time on debugging it to find the problem, they would be more encouraged to write them.</p>\n\n<p>Here\'s a tool which provides such functionality:</p>\n\n<p><a href="http://www.wisetester.com/" rel="nofollow">unit test regression analysis tool</a></p>\n'}, {'answer_id': 4487768, 'author': 'Trystan Spangler', 'author_id': 548014, 'author_profile': 'https://Stackoverflow.com/users/548014', 'pm_score': 1, 'selected': False, 'text': '<p>@George Stocker "Unfortunately our code base does not lend itself to easy testing.". Everyone agrees that there are benefits to unit testing but it sounds like for this code base the costs are high. If the costs are greater than the benefits then why should they be enthusiastic about it? Listen to your coworkers; maybe for them the perceived pain of unit tests is greater than the perceived value of unit tests.</p>\n\n<p>Specifically, try to gain value as soon as possible, and not some feel-goodery "xUnit is green" value, but clean code that users and maintainers value. Maybe you have to mandate unit tests for one iteration and then discuss if it is worth the effort or not.</p>\n'}, {'answer_id': 5117039, 'author': 'DSblizzard', 'author_id': 263485, 'author_profile': 'https://Stackoverflow.com/users/263485', 'pm_score': 2, 'selected': False, 'text': '<p>I\'m agree with the point of view opposite to the majority here:\n<a href="http://blogs.msdn.com/b/cashto/archive/2009/03/31/it-s-ok-not-to-write-unit-tests.aspx" rel="nofollow">It\'s OK Not to Write Unit Tests</a>\nEspecially prototype-heavy programming (AI for example) is difficult to combine with unit testing.</p>\n'}, {'answer_id': 7619171, 'author': 'Samuel Åslund', 'author_id': 974280, 'author_profile': 'https://Stackoverflow.com/users/974280', 'pm_score': 2, 'selected': False, 'text': '<p>One thing no-one has mentioned yet is getting the commitment of all developers to actually run and update any existing automated test. Automated tests that you get back to and find broken because of new development looses a lot of the value and make automated testing really painful. Most of those tests will not be indicating bugs since the developer has tested the code manually, so the time spent updating them is just waste.</p>\n\n<p>Convincing the skeptics to not destroy the work the others are doing on unit-tests is a lot more important for getting value from the testing and might be easier.</p>\n\n<p>Spending hours updating tests that has broken because of new features each time you update from the repository is neither productive nor fun.</p>\n'}, {'answer_id': 8877830, 'author': 'RoiG', 'author_id': 1151351, 'author_profile': 'https://Stackoverflow.com/users/1151351', 'pm_score': 0, 'selected': False, 'text': '<p>Unit Testing is one of the most adopted methodologies for high quality code. Its contribution to a more stable, independent and documented code is well proven . Unit test code is considered and handled as an a integral part of your repository, and as such requires development and maintenance. However, developers often encounter a situation where the resources invested in unit tests where not as fruitful as one would expect.\nIn an ideal world every method we code will have a series of tests covering it’s code and validating it’s correctness. However, usually due to time limitations we either skip some tests or write poor quality ones. In such reality, while keeping in mind the amount of resources invested in unit testing development and maintenance, one must ask himself, given the available time, which code deserve testing the most? And from the existing tests, which tests are actually worth keeping and maintaining? See <a href="http://developer4life.blogspot.com/2012/01/effective-unit-testing-not-all-code-is.html" rel="nofollow">here</a></p>\n'}]
['https://Stackoverflow.com/questions/67299', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9431/']