<p>Using C#, I need a class called <code>User</code> that has a username, password, active flag, first name, last name, full name, etc.  </p>

<p>There should be methods to <em>authenticate</em> and <em>save</em> a user.  Do I just write a test for the methods? And do I even need to worry about testing the properties since they are .Net's getter and setters?</p>

[{'answer_id': 62662, 'author': 'UnkwnTech', 'author_id': 115, 'author_profile': 'https://Stackoverflow.com/users/115', 'pm_score': -1, 'selected': False, 'text': "<p>I can't speak for C# specificly, but when I write unit tests I test EVERY input, even those the user does not do, that way I know how to prevent my own mistakes.</p>\n"}, {'answer_id': 62669, 'author': 'Slavo', 'author_id': 1801, 'author_profile': 'https://Stackoverflow.com/users/1801', 'pm_score': 3, 'selected': False, 'text': "<p>The rule is that you have to test every piece of logic you write. If you implemented some specific functionality in the getters and setters I think they are worth testing. If they only assign values to some private fields, don't bother. </p>\n"}, {'answer_id': 62671, 'author': 'Onorio Catenacci', 'author_id': 2820, 'author_profile': 'https://Stackoverflow.com/users/2820', 'pm_score': 1, 'selected': False, 'text': '<p>As I understand unit tests in the context of agile development, Mike, yes, you need to test the getters and setters (assuming they\'re publicly visible).  The whole concept of unit testing is to test the software unit, which is a class in this case, as a <a href="http://en.wikipedia.org/wiki/Black_box_testing" rel="nofollow noreferrer">black box</a>.  Since the getters and setters are externally visible you need to test them along with Authenticate and Save.</p>\n'}, {'answer_id': 62672, 'author': 'Bob King', 'author_id': 6897, 'author_profile': 'https://Stackoverflow.com/users/6897', 'pm_score': 2, 'selected': False, 'text': "<p>It doesn't hurt to write unit tests for your getters and setters. Right now, they may just be doing field get/sets under the hood, but in the future you may have validation logic, or inter-property dependencies that need to be tested. It's easier to write it now while you're thinking about it then remembering to retrofit it if that time ever comes.</p>\n"}, {'answer_id': 62673, 'author': 'Tom Walker', 'author_id': 6951, 'author_profile': 'https://Stackoverflow.com/users/6951', 'pm_score': 1, 'selected': False, 'text': '<p>If the Authenticate and Save methods use the properties, then your tests will indirectly touch the properties. As long as the properties are just providing access to data, then explicit testing should not be necessary (unless you are going for 100% coverage).</p>\n'}, {'answer_id': 62682, 'author': 'Tim Howland', 'author_id': 4276, 'author_profile': 'https://Stackoverflow.com/users/4276', 'pm_score': 6, 'selected': False, 'text': "<p>Test your code, not the language.</p>\n\n<p>A unit test like:</p>\n\n<pre><code>Integer i = new Integer(7);\nassert (i.instanceOf(integer));\n</code></pre>\n\n<p>is only useful if you are writing a compiler and there is a non-zero chance that your <code>instanceof</code> method is not working.</p>\n\n<p>Don't test stuff that you can rely on the language to enforce. In your case, I'd focus on your authenticate and save methods - and I'd write tests that made sure they could handle null values in any or all of those fields gracefully.</p>\n"}, {'answer_id': 62684, 'author': 'Peter Bernier', 'author_id': 6112, 'author_profile': 'https://Stackoverflow.com/users/6112', 'pm_score': 1, 'selected': False, 'text': "<p>I would test your getters and setters. Depending on who's writing the code, some people change the meaning of the getter/setter methods. I've seen variable initialization and other validation as part of getter methods. In order to test this sort of thing, you'd want unit tests covering that code explicitly.</p>\n"}, {'answer_id': 62685, 'author': 'tronda', 'author_id': 6896, 'author_profile': 'https://Stackoverflow.com/users/6896', 'pm_score': 1, 'selected': False, 'text': '<p>Personally I would "test anything that can break" and simple getter (or even better auto properties) will not break. I have never had a simple return statement fail and therefor never have test for them. If the getters have calculation within them or some other form of statements, I would certainly add tests for them.</p>\n\n<p>Personally I use <a href="http://code.google.com/p/moq" rel="nofollow noreferrer">Moq</a> as a mock object framework and then verify that my object calls the surrounding objects the way it should. </p>\n'}, {'answer_id': 62696, 'author': 'm_pGladiator', 'author_id': 446104, 'author_profile': 'https://Stackoverflow.com/users/446104', 'pm_score': 1, 'selected': False, 'text': "<p>You have to cover the execution of every method of the class with UT and check the method return value. This includes getters and setters, especially in case the members(properties) are complex classes, which requires large memory allocation during their initialization. Call the setter with some very large string for example (or something with greek symbols) and check the result is correct (not truncated, encoding is good e.t.c.)</p>\n\n<p>In case of simple integers that also applies - what happens if you pass long instead of integer? That's the reason you write UT for :)</p>\n"}, {'answer_id': 62698, 'author': 'Steve Cooper', 'author_id': 6722, 'author_profile': 'https://Stackoverflow.com/users/6722', 'pm_score': 4, 'selected': False, 'text': "<p>If they really are trivial, then don't bother testing. Eg, if they are implemented like this;</p>\n\n<pre><code>public class User\n{\n    public string Username { get; set; }\n    public string Password { get; set; }\n}\n</code></pre>\n\n<p>If, on the other hand, you are doing something clever, (like encrypting and decrypting the password in the getter/setter) then give it a test. </p>\n"}, {'answer_id': 62700, 'author': 'Crippledsmurf', 'author_id': 35031, 'author_profile': 'https://Stackoverflow.com/users/35031', 'pm_score': 1, 'selected': False, 'text': '<p>Testing of a class should verify that:</p>\n\n<ol>\n<li>methods and properties return expected values  </li>\n<li>Appropriate excepts are thrown when an invalid argument is supplied  </li>\n<li>Interactions between the class and other objects occur as expected when a given method is called</li>\n</ol>\n\n<p>Of course if the getters and setters have no special logic then the tests of the Authenticate andSave methods should cover them, but otherwise an explict test should be written</p>\n'}, {'answer_id': 62706, 'author': 'Mike Becatti', 'author_id': 6617, 'author_profile': 'https://Stackoverflow.com/users/6617', 'pm_score': 1, 'selected': False, 'text': "<p>I wouldn't test the actual setting of properties.  I would be more concerned about how those properties get populated by the consumer, and what they populate them with.  With any testing, you have to weigh the risks with the time/cost of testing.  </p>\n"}, {'answer_id': 62709, 'author': 'user7015', 'author_id': 7015, 'author_profile': 'https://Stackoverflow.com/users/7015', 'pm_score': 1, 'selected': False, 'text': '<p>You should test "every non-trivial block of code" using unit tests as far as possible.</p>\n\n<p>If your properties are trivial and its unlikely that someone will introduce a bug in it, then it should be safe to not unit test them.</p>\n\n<p>Your Authenticate() and Save() methods look like good candidates for testing.</p>\n'}, {'answer_id': 62715, 'author': 'warren_s', 'author_id': 6255, 'author_profile': 'https://Stackoverflow.com/users/6255', 'pm_score': 2, 'selected': False, 'text': "<p>Testing boilerplate code is a waste of time, but as Slavo says, if you add a side effect to your getters/setters, then you should write a test to accompany that functionality.</p>\n\n<p>If you're doing test-driven development, you should write the contract (eg interface) first, then write the test(s) to exercise that interface which document the expected results/behaviour. <strong>Then</strong> write your methods themselves, without touching the code in your unit tests. Finally, grab a code coverage tool and make sure your tests exercise all the logic paths in your code.</p>\n"}, {'answer_id': 62721, 'author': 'Simon Johnson', 'author_id': 854, 'author_profile': 'https://Stackoverflow.com/users/854', 'pm_score': 1, 'selected': False, 'text': "<p>Ideally, you would have done your unit tests as you were writing the class. This is how you're meant to do it when using Test Driven Development. You add the tests as you implement each function point, making sure that you cover the edge-cases with test too.</p>\n\n<p>Writing the tests afterwards is much more painful, but doable.</p>\n\n<p>Here's what I'd do in your position:</p>\n\n<ol>\n<li>Write a basic set of tests that test the core function.</li>\n<li>Get NCover and run it on your tests. Your test coverage will probably be around 50% at this point.</li>\n<li>Keep adding tests that cover your edge-cases until you get coverage of around 80%-90%</li>\n</ol>\n\n<p>This should give you a nice working set of unit tests that will act as a good buffer against regressions. </p>\n\n<p>The only problem with this approach is that code has to be <em>designed</em> to be testable in this fashion. If you made any coupling mistakes early on, you won't be able to get high coverage very easily. </p>\n\n<p>This is why it is really important to write the tests before you write the code. It forces you to write code that is loosely coupled. </p>\n"}, {'answer_id': 62727, 'author': 'erlando', 'author_id': 4192, 'author_profile': 'https://Stackoverflow.com/users/4192', 'pm_score': 1, 'selected': False, 'text': '<p>Don\'t test obviously working (boilerplate) code. So if your setters and getters are just "propertyvalue = value" and "return propertyvalue" it makes no sense to test it.</p>\n'}, {'answer_id': 62735, 'author': 'CestLaGalere', 'author_id': 6684, 'author_profile': 'https://Stackoverflow.com/users/6684', 'pm_score': 1, 'selected': False, 'text': '<p>Even get / set can have odd consequences, depending upon how they have been implemented, so they should be treated as methods.</p>\n\n<p>Each test of these will need to specify sets of parameters for the properties, defining both acceptable and unacceptable properties to ensure the calls return / fail in the expected manner.</p>\n\n<p>You also need to be aware of security gotchas, as an example SQL injection, and test for these.</p>\n\n<p>So yes, you do need to worry about testing the properties.</p>\n'}, {'answer_id': 62749, 'author': 'Mendelt', 'author_id': 3320, 'author_profile': 'https://Stackoverflow.com/users/3320', 'pm_score': 2, 'selected': False, 'text': "<p>Really trivial code like getters and setters that have no extra behaviour than setting a private field are overkill to test. In 3.0 C# even has some syntactic sugar where the compiler takes care of the private field so you don't have to program  that.</p>\n\n<p>I usually write lots of very simple tests verifying behaviour I expect from my classes. Even if it's simple stuff like adding two numbers. I switch a lot between writing a simple test and writing some lines of code. The reason for this is that I then can change around code without being afraid I broke things I didn't think about.</p>\n"}, {'answer_id': 62750, 'author': 'Rik', 'author_id': 5409, 'author_profile': 'https://Stackoverflow.com/users/5409', 'pm_score': 2, 'selected': False, 'text': '<p>in general, when a method is only defined for certain values, test for values on <em>and over</em> the border of what is acceptable. In other words, make sure your method does what it\'s supposed to do, <em>but nothing more</em>. This is important, because when you\'re going to fail, you want to fail early.</p>\n\n<p>In inheritance hierarchies, make sure to test for <a href="http://en.wikipedia.org/wiki/Liskov_substitution_principle" rel="nofollow noreferrer">LSP</a> compliance. </p>\n\n<p>Testing default getters and setters doesn\'t seem very useful to me, unless you\'re planning to do some validation later on.</p>\n'}, {'answer_id': 62760, 'author': 'Andrei Savu', 'author_id': 3885, 'author_profile': 'https://Stackoverflow.com/users/3885', 'pm_score': 1, 'selected': False, 'text': "<p>I believe it's silly to test getters &amp; setters when they only make a simple operation. Personally I don't write complex unit tests to cover any usage pattern. I try to write enough tests to ensure I have handled the normal execution behavior and as much error cases I can think of. I will write more unit tests as a response to bug reports. I use unit test to ensure the code meets the requirements and to make future modification easier. I feel a lot more willing to change code when I know that if I break something a test will fail.  </p>\n"}, {'answer_id': 62779, 'author': 'Rob Cooper', 'author_id': 832, 'author_profile': 'https://Stackoverflow.com/users/832', 'pm_score': 8, 'selected': True, 'text': '<p>Many great responses to this are also on my question: "<a href="https://stackoverflow.com/questions/24965/beginning-tdd-challenges-solutions-recommendations">Beginning TDD - Challenges? Solutions? Recommendations?</a>"</p>\n\n<p>May I also recommend taking a look at my <a href="http://cantgrokwontgrok.blogspot.com/2008/09/tdd-getting-started-with-test-driven.html" rel="noreferrer">blog post</a> (which was partly inspired by my question), I have got some good feedback on that. Namely:</p>\n\n<blockquote>\n  <p><strong>I Don’t Know Where to Start?</strong></p>\n  \n  <ul>\n  <li>Start afresh. Only think about writing tests when you are writing new\n  code. This can be re-working of old\n  code, or a completely new feature.</li>\n  <li>Start simple. Don’t go running off and trying to get your head round\n  a testing framework as well as being\n  TDD-esque. Debug.Assert works fine.\n  Use it as a starting point. It doesn’t\n  mess with your project or create\n  dependencies.</li>\n  <li>Start positive. You are trying to improve your craft, feel good about\n  it. I have seen plenty of developers\n  out there that are happy to stagnate\n  and not try new things to better\n  themselves. You are doing the right\n  thing, remember this and it will help\n  stop you from giving up.</li>\n  <li>Start ready for a challenge. It is quite hard to start getting into\n  testing. Expect a challenge, but\n  remember – challenges can be overcome.</li>\n  </ul>\n  \n  <p><strong>Only Test For What You Expect</strong></p>\n  \n  <p>I had real problems when I first\n  started because I was constantly sat\n  there trying to figure out every\n  possible problem that could occur and\n  then trying to test for it and fix.\n  This is a quick way to a headache.\n  Testing should be a real YAGNI\n  process. If you know there is a\n  problem, then write a test for it.\n  Otherwise, don’t bother.</p>\n  \n  <p><strong>Only Test One Thing</strong></p>\n  \n  <p>Each test case should only ever test\n  one thing. If you ever find yourself\n  putting “and” in the test case name,\n  you’re doing something wrong.</p>\n</blockquote>\n\n<p>I hope this means we can move on from "getters and setters" :)</p>\n'}, {'answer_id': 62825, 'author': 'Dean Poulin', 'author_id': 5462, 'author_profile': 'https://Stackoverflow.com/users/5462', 'pm_score': 1, 'selected': False, 'text': '<p>I would write a test for anything that you are writing code for that is testable outside of the GUI interface.</p>\n\n<p>Typically, any logic that I write that has any business logic I place inside another tier or business logic layer.</p>\n\n<p>Then writing tests for anything that does something is easy to do.</p>\n\n<p>First pass, write a unit test for each public method in your "Business Logic Layer".</p>\n\n<p>If I had a class like this:</p>\n\n<pre><code>   public class AccountService\n    {\n        public void DebitAccount(int accountNumber, double amount)\n        {\n\n        }\n\n        public void CreditAccount(int accountNumber, double amount)\n        {\n\n        }\n\n        public void CloseAccount(int accountNumber)\n        {\n\n        }\n    }\n</code></pre>\n\n<p>The first thing I would do before I wrote any code knowing that I had these actions to perform would be to start writing unit tests.</p>\n\n<pre><code>   [TestFixture]\n    public class AccountServiceTests\n    {\n        [Test]\n        public void DebitAccountTest()\n        {\n\n        }\n\n        [Test]\n        public void CreditAccountTest()\n        {\n\n        }\n\n        [Test]\n        public void CloseAccountTest()\n        {\n\n        }\n    }\n</code></pre>\n\n<p>Write your tests to validate the code you\'ve written to do something.  If you iterating over a collection of things, and changing something about each of them, write a test that does the same thing and Assert that actually happened.</p>\n\n<p>There\'s a lot of other approaches you can take, namely Behavoir Driven Development (BDD), that\'s more involved and not a great place to start with your unit testing skills.</p>\n\n<p>So, the moral of the story is, test anything that does anything you might be worried about, keep the unit tests testing specific things that are small in size, a lot of tests are good.</p>\n\n<p>Keep your business logic outside of the User Interface layer so that you can easily write tests for them, and you\'ll be good.</p>\n\n<p>I recommend <a href="http://testdriven.net/" rel="nofollow noreferrer">TestDriven.Net</a> or <a href="http://www.jetbrains.com/resharper/" rel="nofollow noreferrer">ReSharper</a> as both easily integrate into Visual Studio.</p>\n'}, {'answer_id': 63044, 'author': 'pmlarocque', 'author_id': 7419, 'author_profile': 'https://Stackoverflow.com/users/7419', 'pm_score': 2, 'selected': False, 'text': "<p>well if you think it can break, write a test for it. I usually don't test setter/getter, but lets says you make one for User.Name, which concatenate first and last name, I would write a test so if someone change the order for last and first name, at least he would know he changed something that was tested. </p>\n"}, {'answer_id': 63054, 'author': 'Eric Normand', 'author_id': 7492, 'author_profile': 'https://Stackoverflow.com/users/7492', 'pm_score': 2, 'selected': False, 'text': '<p>The canonical answer is "test anything that can possibly break."  If you are sure the properties won\'t break, don\'t test them.</p>\n\n<p>And once something is found to have broken (you find a bug), obviously it means you need to test it.  Write a test to reproduce the bug, watch it fail, then fix the bug, then watch the test pass.</p>\n'}, {'answer_id': 63131, 'author': 'Sklivvz', 'author_id': 7028, 'author_profile': 'https://Stackoverflow.com/users/7028', 'pm_score': 2, 'selected': False, 'text': '<p>You should test everything. Right now you have getters and setters, but one day you might change them somewhat, maybe to do validation or something else. The tests you write today will be used tomorrow to make sure everything keeps on working as usual.\nWhen you write test, you should forget considerations like "right now it\'s trivial". In an agile or test-driven context you should test assuming future refactoring.\nAlso, did you try putting in really weird values like extremely long strings, or other "bad" content? Well you should... never assume how badly your code can be abused in the future.</p>\n\n<p>Generally I find that writing extensive user tests is on one side, exhausting. On the other side, though it always gives you invaluable insight on how your application should work and helps you throw away easy (and false) assumptions (like: the user name will always be less than 1000 characters in length).</p>\n'}, {'answer_id': 63213, 'author': 'Scott Lawrence', 'author_id': 3475, 'author_profile': 'https://Stackoverflow.com/users/3475', 'pm_score': 1, 'selected': False, 'text': '<p>I would recommend writing multiple tests for your Authenticate and Save methods.  In addition to the success case (where all parameters are provided, everything is correctly spelled, etc), it\'s good to have tests for various failure cases (incorrect or missing parameters, unavailable database connections if applicable, etc).  I recommend <a href="http://www.pragprog.com/titles/utc2/pragmatic-unit-testing-in-c-with-nunit" rel="nofollow noreferrer">Pragmatic Unit Testing in C# with NUnit</a> as a reference. </p>\n\n<p>As others have stated, unit tests for getters and setters are overkill, unless there\'s conditional logic in your getters and setters.  </p>\n'}, {'answer_id': 63222, 'author': 'Dirigible', 'author_id': 7662, 'author_profile': 'https://Stackoverflow.com/users/7662', 'pm_score': 2, 'selected': False, 'text': '<p>For simple modules that may end up in a toolkit, or in an open source type of project, you should test as much as possible including the trivial getters and setters.  The thing you want to keep in mind is that generating a unit test as you write a particular module is fairly simple and straight forward.  Adding getters and setters is minimal code and can be handled without much thought.  However, once your code is placed in a larger system, this extra effort can protect you against changes in the underlying system, such as type changes in a base class.  Testing everthing is the best way to have a regression that is complete.  </p>\n'}, {'answer_id': 63587, 'author': 'Ray Hayes', 'author_id': 7093, 'author_profile': 'https://Stackoverflow.com/users/7093', 'pm_score': 1, 'selected': False, 'text': '<p>Whilst it is possible to correctly guess where your code needs testing, I generally think you need metrics to back up this guess.  Unit testing in my view goes hand in hand with code-coverage metrics.</p>\n\n<p>Code with lots of tests but a small coverage hasn\'t been well tested.  That said, code with 100% coverage but not testing the boundry and error cases is also not great.</p>\n\n<p>You want a balance between high coverage (90% minimum) and variable input data.</p>\n\n<p>Remember to test for "garbage in"!</p>\n\n<p>Also, a unit-test is not a unit-test unless it checks for a failure.  Unit-tests that don\'t have asserts or are marked with known exceptions will simply test that the code doesn\'t die when run!  </p>\n\n<p>You need to design your tests so that they always report failures or unexpected/unwanted data!</p>\n'}, {'answer_id': 63750, 'author': 'Scott Saad', 'author_id': 4916, 'author_profile': 'https://Stackoverflow.com/users/4916', 'pm_score': 1, 'selected': False, 'text': '<h1>It makes our code better... period!</h1>\n<p>One thing us software developers forget about when doing test driven development is the purpose behind our actions. If a unit test is being written after the production code is already in place, the value of the test goes way down (but is not completely lost).</p>\n<p>In the true spirit for unit testing, these tests are <strong>not</strong> primarily there to &quot;test&quot; more of our code; or to get 90%-100% better code coverage. These are all <strong>fringe benefits</strong> of writing the tests first. The big payoff is that our production code ends be be written much better due to the natural process of TDD.</p>\n<p>To help better communicate this idea, the following may be helpful in reading:</p>\n<p><a href="http://michaelfeathers.typepad.com/michael_feathers_blog/2008/06/the-flawed-theo.html" rel="nofollow noreferrer">The Flawed Theory of Unit Tests</a><br />\n<a href="http://blog.saadware.com/2008/07/02/purposeful-software-development/" rel="nofollow noreferrer">Purposeful Software Development</a></p>\n<p>If we feel that the act of writing <strong>more unit tests</strong> is what helps us gain a higher quality product, then we may be suffering from a <a href="http://en.wikipedia.org/wiki/Cargo_cult_programming" rel="nofollow noreferrer">Cargo Cult</a> of Test Driven Development.</p>\n'}, {'answer_id': 63844, 'author': 'Manrico Corazzi', 'author_id': 4690, 'author_profile': 'https://Stackoverflow.com/users/4690', 'pm_score': 0, 'selected': False, 'text': '<p>I second <strong>test anything that can possibly break</strong> and <strong>don\'t write silly tests</strong>. But the most important tenet is <strong>test anything that you find is broken</strong>: if some method behaves oddly write a test to outline the data set that makes it fail, then correct the bug and watch the bar go green. Also test the "boundary" data values (null, 0, MAX_INT, empty lists, whatever).</p>\n'}, {'answer_id': 63874, 'author': 'Dan', 'author_id': 8040, 'author_profile': 'https://Stackoverflow.com/users/8040', 'pm_score': 0, 'selected': False, 'text': "<p>When writing unit tests, or really any test, you determine what to test by looking at the boundary conditions of what you're testing. For example, you have a function called is_prime. Fortunately, it does what it's name implies and tells you whether the integer object is prime or not. For this I am assuming you are using objects. Now, we would need to check that valid results occurred for a known range of prime and non-prime objects. That's your starting point.</p>\n\n<p>Basically, look at what should happen with a function, method, program, or script, and then at what should definitely <em>not</em> happen with that same code. That's the basis for your test. Just be prepared to modify your tests as you become more knowledgeable on what <strong><em>should</em></strong> be happening with your code.</p>\n"}, {'answer_id': 65743, 'author': 'user9397', 'author_id': 9397, 'author_profile': 'https://Stackoverflow.com/users/9397', 'pm_score': 2, 'selected': False, 'text': '<p>Another canonical answer.  This, I believe, from Ron Jeffries: </p>\n\n<blockquote>\n  <p>Only test the code that you want to work.</p>\n</blockquote>\n'}, {'answer_id': 66387, 'author': 'pjesi', 'author_id': 1296737, 'author_profile': 'https://Stackoverflow.com/users/1296737', 'pm_score': 0, 'selected': False, 'text': '<p>Writing code that has no value is always a bad idea. Since the proposed test adds no value to your project (or very close to it). Then your are wasting valuable time that you could spend writing code that actually brings value.</p>\n'}, {'answer_id': 69259, 'author': 'eroijen', 'author_id': 10829, 'author_profile': 'https://Stackoverflow.com/users/10829', 'pm_score': 5, 'selected': False, 'text': '<p><strong>This got me into unit testing and it made me very happy</strong></p>\n\n<p>We just started to do unit testing.\nFor a long time I knew it would be good to start doing it but I had no idea how to start and more importantly what to test.</p>\n\n<p>Then we had to rewrite an important piece of code in our accounting program.\nThis part was very complex as it involved a lot of different scenarios.\nThe part I\'m talking about is a method to pay sales and/or purchase invoices already entered into the accounting system.</p>\n\n<p>I just didn\'t know how to start coding it, as there were so many different payment options.\nAn invoice could be $100 but the customer only transferred $99.\nMaybe you have sent sales invoices to a customer but you have also purchased from that customer.\nSo you sold him for $300 but you bought for $100. You can expect your customer to pay you $200 to settle the balance.\nAnd what if you sold for $500 but the customer pays you only $250?</p>\n\n<p>So I had a very complex problem to solve with many possibilities that one scenario would work perfectly but would be wrong on an other type of invocie/payment combination.</p>\n\n<p><strong>This is where unit testing came to the rescue.</strong></p>\n\n<p>I started to write (inside the test code) a method to create a list of invoices, both for sales and purchases.\nThen I wrote a second method to create the actual payment. \nNormally a user would enter that information through a user interface.</p>\n\n<p>Then I created the first TestMethod, testing a very simple payment of a single invoice without any payment discounts.\nAll the action in the system would happen when a bankpayment would be saved to the database.\nAs you can see I created an invoice, created a payment (a bank transaction) and saved the transaction to disk.\nIn my asserts I put what should be the correct numbers ending up in the Bank transaction and in the linked Invoice.\nI check for the number of payments, the payment amounts, the discount amount and the balance of the invoice after the transaction.</p>\n\n<p>After the test ran I would go to the database and double check if what I expected was there.</p>\n\n<p><strong>After</strong> I wrote the test, I started coding the payment method (part of the BankHeader class).\nIn the coding I only bothered with code to make the first test pass. I did not yet think about the other, more complex, scenarios.</p>\n\n<p>I ran the first test, fixed a small bug until my test would pass.</p>\n\n<p>Then I started to write the second test, this time working with a payment discount.\nAfter I wrote the test I modified the payment method to support discounts.</p>\n\n<p>While testing for correctness with a payment discount, I also tested the simple payment.\nBoth tests should pass of course.</p>\n\n<p><strong>Then I worked my way down to the more complex scenarios.</strong></p>\n\n<p>1) Think of a new scenario   </p>\n\n<p>2) Write a test for that scenario</p>\n\n<p>3) Run that single test to see if it would pass</p>\n\n<p>4) If it didn\'t I\'d debug and modify the code until it would pass. </p>\n\n<p>5) While modifying code I kept on running all tests</p>\n\n<p>This is how I managed to create my very complex payment method.\nWithout unit testing I did not know how to start coding, the problem seemed overwhelming.\nWith testing I could start with a simple method and extend it step by step with the assurance that the simpler scenarios would still work.</p>\n\n<p>I\'m sure that using unit testing saved me a few days (or weeks) of coding and is more or less guaranteeing the correctness of my method.</p>\n\n<p>If I later think of a new scenario, I can just add it to the tests to see if it is working or not.\nIf not I can modify the code but still be sure the other scenarios are still working correctly.\nThis will save days and days in the maintenance and bug fixing phase.</p>\n\n<p><strong>Yes, even tested code can still have bugs if a user does things you did not think of or prevented him from doing</strong></p>\n\n<p>Below are just some of tests I created to test my payment method.</p>\n\n<pre><code>public class TestPayments\n{\n    InvoiceDiaryHeader invoiceHeader = null;\n    InvoiceDiaryDetail invoiceDetail = null;\n    BankCashDiaryHeader bankHeader = null;\n    BankCashDiaryDetail bankDetail = null;\n\n\n\n    public InvoiceDiaryHeader CreateSales(string amountIncVat, bool sales, int invoiceNumber, string date)\n    {\n        ......\n        ......\n    }\n\n    public BankCashDiaryHeader CreateMultiplePayments(IList&lt;InvoiceDiaryHeader&gt; invoices, int headerNumber, decimal amount, decimal discount)\n    {\n       ......\n       ......\n       ......\n    }\n\n\n    [TestMethod]\n    public void TestSingleSalesPaymentNoDiscount()\n    {\n        IList&lt;InvoiceDiaryHeader&gt; list = new List&lt;InvoiceDiaryHeader&gt;();\n        list.Add(CreateSales("119", true, 1, "01-09-2008"));\n        bankHeader = CreateMultiplePayments(list, 1, 119.00M, 0);\n        bankHeader.Save();\n\n        Assert.AreEqual(1, bankHeader.BankCashDetails.Count);\n        Assert.AreEqual(1, bankHeader.BankCashDetails[0].Payments.Count);\n        Assert.AreEqual(119M, bankHeader.BankCashDetails[0].Payments[0].PaymentAmount);\n        Assert.AreEqual(0M, bankHeader.BankCashDetails[0].Payments[0].PaymentDiscount);\n        Assert.AreEqual(0, bankHeader.BankCashDetails[0].Payments[0].InvoiceHeader.Balance);\n    }\n\n    [TestMethod]\n    public void TestSingleSalesPaymentDiscount()\n    {\n        IList&lt;InvoiceDiaryHeader&gt; list = new List&lt;InvoiceDiaryHeader&gt;();\n        list.Add(CreateSales("119", true, 2, "01-09-2008"));\n        bankHeader = CreateMultiplePayments(list, 2, 118.00M, 1M);\n        bankHeader.Save();\n\n        Assert.AreEqual(1, bankHeader.BankCashDetails.Count);\n        Assert.AreEqual(1, bankHeader.BankCashDetails[0].Payments.Count);\n        Assert.AreEqual(118M, bankHeader.BankCashDetails[0].Payments[0].PaymentAmount);\n        Assert.AreEqual(1M, bankHeader.BankCashDetails[0].Payments[0].PaymentDiscount);\n        Assert.AreEqual(0, bankHeader.BankCashDetails[0].Payments[0].InvoiceHeader.Balance);\n    }\n\n    [TestMethod]\n    [ExpectedException(typeof(ApplicationException))]\n    public void TestDuplicateInvoiceNumber()\n    {\n        IList&lt;InvoiceDiaryHeader&gt; list = new List&lt;InvoiceDiaryHeader&gt;();\n        list.Add(CreateSales("100", true, 2, "01-09-2008"));\n        list.Add(CreateSales("200", true, 2, "01-09-2008"));\n\n        bankHeader = CreateMultiplePayments(list, 3, 300, 0);\n        bankHeader.Save();\n        Assert.Fail("expected an ApplicationException");\n    }\n\n    [TestMethod]\n    public void TestMultipleSalesPaymentWithPaymentDiscount()\n    {\n        IList&lt;InvoiceDiaryHeader&gt; list = new List&lt;InvoiceDiaryHeader&gt;();\n        list.Add(CreateSales("119", true, 11, "01-09-2008"));\n        list.Add(CreateSales("400", true, 12, "02-09-2008"));\n        list.Add(CreateSales("600", true, 13, "03-09-2008"));\n        list.Add(CreateSales("25,40", true, 14, "04-09-2008"));\n\n        bankHeader = CreateMultiplePayments(list, 5, 1144.00M, 0.40M);\n        bankHeader.Save();\n\n        Assert.AreEqual(1, bankHeader.BankCashDetails.Count);\n        Assert.AreEqual(4, bankHeader.BankCashDetails[0].Payments.Count);\n        Assert.AreEqual(118.60M, bankHeader.BankCashDetails[0].Payments[0].PaymentAmount);\n        Assert.AreEqual(400, bankHeader.BankCashDetails[0].Payments[1].PaymentAmount);\n        Assert.AreEqual(600, bankHeader.BankCashDetails[0].Payments[2].PaymentAmount);\n        Assert.AreEqual(25.40M, bankHeader.BankCashDetails[0].Payments[3].PaymentAmount);\n\n        Assert.AreEqual(0.40M, bankHeader.BankCashDetails[0].Payments[0].PaymentDiscount);\n        Assert.AreEqual(0, bankHeader.BankCashDetails[0].Payments[1].PaymentDiscount);\n        Assert.AreEqual(0, bankHeader.BankCashDetails[0].Payments[2].PaymentDiscount);\n        Assert.AreEqual(0, bankHeader.BankCashDetails[0].Payments[3].PaymentDiscount);\n\n        Assert.AreEqual(0, bankHeader.BankCashDetails[0].Payments[0].InvoiceHeader.Balance);\n        Assert.AreEqual(0, bankHeader.BankCashDetails[0].Payments[1].InvoiceHeader.Balance);\n        Assert.AreEqual(0, bankHeader.BankCashDetails[0].Payments[2].InvoiceHeader.Balance);\n        Assert.AreEqual(0, bankHeader.BankCashDetails[0].Payments[3].InvoiceHeader.Balance);\n    }\n\n    [TestMethod]\n    public void TestSettlement()\n    {\n        IList&lt;InvoiceDiaryHeader&gt; list = new List&lt;InvoiceDiaryHeader&gt;();\n        list.Add(CreateSales("300", true, 43, "01-09-2008")); //Sales\n        list.Add(CreateSales("100", false, 6453, "02-09-2008")); //Purchase\n\n        bankHeader = CreateMultiplePayments(list, 22, 200, 0);\n        bankHeader.Save();\n\n        Assert.AreEqual(1, bankHeader.BankCashDetails.Count);\n        Assert.AreEqual(2, bankHeader.BankCashDetails[0].Payments.Count);\n        Assert.AreEqual(300, bankHeader.BankCashDetails[0].Payments[0].PaymentAmount);\n        Assert.AreEqual(-100, bankHeader.BankCashDetails[0].Payments[1].PaymentAmount);\n        Assert.AreEqual(0, bankHeader.BankCashDetails[0].Payments[0].InvoiceHeader.Balance);\n        Assert.AreEqual(0, bankHeader.BankCashDetails[0].Payments[1].InvoiceHeader.Balance);\n    }\n</code></pre>\n'}, {'answer_id': 2717133, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': "<p>The best rule of thumb I've seen is to test everything that you can't tell at a glance, for certain, will work properly.  Anything more and you wind up testing the language/environment.</p>\n"}, {'answer_id': 29182956, 'author': 'Thomas Carlisle', 'author_id': 4462119, 'author_profile': 'https://Stackoverflow.com/users/4462119', 'pm_score': 3, 'selected': False, 'text': '<p>This question seems to be a question of where does one draw the line on what methods get tested and which don\'t. </p>\n\n<p>The setters and getters for value assignment have been created with consistency and future growth in mind, and foreseeing that some time down the road the setter/getter may evolve into more complex operations. It would make sense to put unit tests of those methods in place, also for the sake of consistency and future growth. </p>\n\n<p>Code reliability, especially while undergoing change to add additional functionality, is the primary goal. I am not aware of anyone ever getting fired for including setters/getters in the testing methodology, but I am certain there exists people who wished they had tested methods which last they were aware or can recall were simple set/get wrappers but that was no longer the case. </p>\n\n<p>Maybe another member of the team expanded the set/get methods to include logic that now needs tested but didn\'t then create the tests. But now your code is calling these methods and you aren\'t aware they changed and need in-depth testing, and the testing you do in development and QA don\'t trigger the defect, but real business data on the first day of release does trigger it. </p>\n\n<p>The two teammates will now debate over who dropped the ball and failed to put in unit tests when the set/gets morphed to include logic that can fail but isn\'t covered by a unit test. The teammate that originally wrote the set/gets will have an easier time coming out of this clean if the tests were implemented from day one on the simple set/gets. </p>\n\n<p>My opinion is that a few minutes of "wasted" time covering ALL methods with unit tests, even trivial ones, might save days of headache down the road and loss of money/reputation of the business and loss of someone\'s job. </p>\n\n<p>And the fact that you did wrap trivial methods with unit tests might be seen by that junior team mate when they change the trivial methods into non-trivial ones and prompt them to update the test, and now nobody is in trouble because the defect was contained from reaching production.</p>\n\n<p>The way we code, and the discipline that can be seen from our code, can help others. </p>\n'}]
['https://Stackoverflow.com/questions/62625', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9938/']