Test driven development


Published on

  • Be the first to comment

  • Be the first to like this

No Downloads
Total Views
On Slideshare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide
  • Add a Test + ensure it failsWrite minimum amout of code to get it to passRefactor code, all the while rerunning tests
  • Test Generation Properties"Mark all test results Inconclusive by default". When this is checked, the method is created with the code:Assert.Inconclusive("Verify the correctness of this test method.");When you run you test, it will always say that your Test is "Inconclusive". When you code is complete and you would like to run your test, remove "Assert.Inconclusive()" call and test it then.enable generation warningTurn on/off the ability to enable generation warnings—that is, reporting if any warnings occur during the code generation process.Globally qualify all types. This setting tells the code generation engine to add a global qualifier (global:: in Microsoft Visual C# 2005) to variable declaration. Use this when you have like-named objects that reside in multiple namespaces. If you do not, the code generation engine will create logic to create the object, but the compiler will not be able to determine which class to create, and will error.Enable/disable documentation comments. This allows you to disable the creation of XML documentation above each Test() methodHonor InternalsVisibleTo AttributeSelect the check box to allow methods that are marked as Friend or Internal to be treated as if they were public methods (recommended)
  • Test driven development

    2. 2. Outline2 Outline 1. Development Approaches 2. What is TDD 3. Code Refactoring 4. Steps to start TDD 5. What can be tested 6. How Does TDD Help 7. Unit Tests 8. Unit Test – Definitions 9. Code Coverage 10. Example 11. Visual Studio Unit Tests Walkthrough
    3. 3. Development Approaches3  Ad hoc development  Writing pseudo code first  Model Driven Development (MDD)  Test Driven Development (TDD)
    4. 4. What is TDD4 Test-Driven Development (TDD) is a software development technique that involves (repeatedly) first writing a test case and then implementing the code necessary to excercise the test (Test case First, Then Code) In TDD: Requirements => Tests => developement Code  Requirements drive the tests.  Tests drive the development of the application code.  No application code is written without writing a failing test first.  Tests are collected in a suite and the suite is run frequently, like every time after code is written.  Test and code are written in elementary increments.  Refactoring is a continuous operation, and is supported by a passing battery of tests.
    5. 5. What is TDD 51. The developer writes an (initially failing) automated test case2. that defines a desired requirement (improvement or new function) .3. He then produces the minimum amount of code to pass that test4. and finally refactors the new code to acceptable standards
    6. 6. What is TDD 6 Test shouldTDD = Test First Development + Refactoring Initially Fail (and for expected•Add a Test + ensure it fails reason)•Write minimum amount of code to get it to pass•Refractor code , all the while re-running tests toensure they pass
    7. 7. Code Refactoring7  Refactoring is a disciplined technique for restructuring an existing body of code, altering its internal structure without changing its external behaviour.  Code Improvement  Refactoring Removes „code smell‟  long methods,  duplicate code,  large classes  Refactoring techniques  Breaking large methods up into smaller, reusable, more logical units  By breaking down code in smaller pieces, it is more easily understandable => less buggy + should be  Move part of code to new class  create more general types to allow for more code sharing
    8. 8. Steps to start TDD8 1) Analyze the requirements + write the list of tasks or features 2) Pick a task or feature  Brainstorm a list of tests for the task or feature  Review the tests list and pick a test 3) Write the test case 1) Write only enough code that the test case compiles 4) Run the test and see running the code fails 5) Write only enough code to just pass the test 6) Refactor the production code and eliminate duplication 7) Repeat
    9. 9. What can be tested9  Valid inputs  Invalid inputs  Errors, exceptions, and events  Boundary conditions  Everything that could possibly break!
    10. 10. How Does TDD Help10  Ensures that your design is clean by focusing on creation of operations that are callable and testable  Shortens the programming feedback loop  Provides detailed specification through tests  Provides concrete evidence that your software works  The suite of unit tests provides constant feedback that each component is still working.  Supports evolutionary development.  The unit tests act as documentation that cannot go out-of-date, unlike separate documentation, which can and frequently does.  The software tends to be better designed, that is, loosely coupled and easily maintainable, because the developer is free to make design decisions and refactor at any time with confidence that the software is still working. This confidence is gained by running the tests. The need for a design pattern may emerge, and the code can be changed at that time.
    11. 11. TDD Advantages11 TDD is good because it:  Aids in understanding (and even defining) requirements  It‟s a practice that adds reliability to the development process  Tests Improve Design  Testing Makes Development Faster, because less time is spent chasing bugs.  catch defects early in the development cycle (earlier is better)  Improves code quality because of the increased modularity, and continuous and relentless refactoring.  Decreases maintenance costs because the code is easier to follow.  Testing is “automated”  If the test fails, its obvious where to look for the problem (if test written correctly i.e test one thing)  Reduces the number of bugs by orders of magnitude,  QA will receive functioning code (they can focus more on end to end and integration)  TDD promotes “small steps”, and lots of them  TDD is risk averse programming, investing work in the near term to avoid failures later on” Munjal Budhabhatti, The Architecture Journal 14
    12. 12. Unit Tests12 General Definition: A method of testing the correctness of a particular module of source code -Wikipedia Testing a method in a class you are writing – while you are writing that class. Chris Donnan
    13. 13. Unit Test - Definitions13  Test Fixture/ Test Class – A class with some unit tests in it.  Test (or Test Method) – a test implemented in a Test Class  Test Suite - A set of test grouped together  Test Harness/ Runner – The tool that actually executes the tests.
    14. 14. Code Coverage14  Code Coverage is an approach or technique that sees you executing [all] the statements and paths through your code-base  Which code has been touched by a test.  Identifies code that your tests missed  Thus, you should find bugs you may not otherwise have found, code coverage “gives you clues”  Identifies code that does not have a test case exercising it  Code coverage can be a useful metric, but it must be used with care  Determine whether high code coverage is a good thing  Simply “touching” every line of code might not be suitable  Do not be sucked into “writing quick tests” just to improve coverage
    15. 15. The tools15  NUnit 2.4.6  Testing framework for .NET  Graphical front-end (clear “black/white” pass/fail indicator)  NCover 1.5.8  “Do you know how much of your code is being tested”  Command-line  Creates an XML output file, XSL transformation for viewing  NCoverExplorer  Graphical front-end for NCover  Windows application that uses NCover‟s XML output file  TestDriven.NET 2.11.2177  NUnit, NCover, NCoverage integration inside the Visual Studio IDE  Right-click context-sensitive menu  Free “liberal” personal edition; commercial Profession and Enterprise editions
    16. 16. Example16  We want to develop a method that,  given two Integers,  returns an Integer that is the sum of parameters.
    17. 17. Example (cont.)17  Test  Method Integer i = new Integer(5); Integer j = new Integer(2); Object o = sum(i,j);
    18. 18. Example (cont.)18  Test  Method Integer i = new public static Object Integer(5); sum(Integer i, Integer j = new Integer(2); Integer j) { Object o = sum(i,j); return new Object(); }
    19. 19. Example (cont.)19  Test  Method Integer i = new public static Object Integer(5); sum(Integer i, Integer j = new Integer(2); Integer j) { Object o = sum(i,j); return new if (o instanceof Integer) Object(); return true; } else return false;
    20. 20. Example (cont.)20  Test  Method Integer i = new public static Integer Integer(5); sum(Integer i, Integer j = new Integer(2); Integer j) { Object o = sum(i,j); return new if (o instanceof Integer) Integer(); return true; } else return false;
    21. 21. Example (cont.)21  Test  Method Integer i = new Integer(5); public static Integer Integer j = new sum(Integer i, Integer(2); Integer j) { Object o = sum(i,j); if (o instanceof Integer) return new Integer(); && ((new Integer(7)).equals(o)) } return true; else return false;
    22. 22. Example (cont.)22  Test  Method Integer i = new Integer(5); public static Integer Integer j = new sum(Integer i, Integer(2); Integer j) { Object o = sum(i,j); if (o instanceof Integer) return new Integer( && ((new Integer(7)).equals(o)) i.intValue() + j.intValue()); return true; else ); return false; }
    23. 23. Questions23
    24. 24. Visual Studio Unit Test WalkThrough Unit Test Overview24  You can create unit tests by 1. using a code generation feature that creates the initial source code of the test, 2. or you can write the test completely by hand. Either way, the test class and all test methods are identified by using programmatic attributes.  Programmatic Attributes (assigned automatically using „Code Generation‟) • Each test class is marked with the [TestClass()] attribute • Each unit test is a test method that is marked with the [TestMethod()] attribute.  The Unit Testing Framework provides many additional Assert classes and other classes that give you flexibility in writing unit test.  The Microsoft.VisualStudio.TestTools.UnitTesting namespace supplies classes that provide unit testing support.  Using unit tests, you can test not only public methods but private methods as well.
    25. 25. Visual Studio Unit Test WalkThrough Creating Unit Tests – Auto Generate25 Select method in class you want to generate test for → Right- click on method name → Select „Create Unit Tests‟
    26. 26. Visual Studio Unit Test WalkThrough Creating Unit Tests – Auto Generate26  Method will be „checked‟ in pop-up box (you can select other methods, I‟ve also selected Credit method!) and click OK.  You can click on settings to update some general setting for Test (I‟ve changed the Test file name to be more descriptive
    27. 27. Visual Studio Unit Test WalkThrough Creating Unit Tests – Auto Generate Each test class is marked with the 27 [TestClass()] attribute1.A separate unit test is created for each method that you select in the Each unit test is a test Create Unit Test dialog box. (here method that is marked we have unit tests for the Credit with the [TestMethod()] and Debit methods. attribute2.Each unit tests that is generated has empty variables and a placeholder Assert statement (the default is usually the Assert.Inconclusive statement. • To make the test meaningful, you have to initialize the variables and replace the placeholder with an appropriate Assert statement.3.When you first generate unit tests, a test project is created in your solution.4.For each class you are testing, a separate unit test file is created. In this example, both of the methods we are testing belong to the same class. Therefore, there is only one unit test file, BankAccountTest.cs.
    28. 28. Visual Studio Unit Tests Creating Unit Tests – Manually28 To manually create a test, right click on Test project -> Add -> New Test
    29. 29. Visual Studio Unit Tests Updating A Unit Test29 Update Test Method to test desired functionality Edit Generated Code To
    30. 30. Visual Studio Unit Tests Running Unit Tests30 View and select test to run View Results of test run Organise Tests into Groups/Lists
    31. 31. Visual Studio Unit Tests Configure Code Coverage31  To see what proportion of your projects code is actually being tested, use the code coverage feature of Microsoft Visual Studio 2010.Double click on“Local.Testing” in thesolution explorer, andselect “Data Anddiagnostics”1.Select „Code coverage‟2.Configure Items to include3.Click Ok and then „Save as‟ and replace existing „local.testing‟ file
    32. 32. Visual Studio Unit Tests Configure Code Coverage32  Ensure „Active Test Settings‟ is set to „local.testsettings‟  Run Tests in „Test List Editor‟  View Coverage Info in „Code coverage Results‟ Window (viewable from Test-→ Windows →Code Coverage Results)
    33. 33. Visual Studio Unit Tests Configure Code Coverage33  Code Coverage Results Window
    34. 34. Appendix – Assert Methods34  Unit Test Framework => Microsoft.VisualStudio.TestTools.UnitTesting  Assert Methods  Inconclusive() : Indicates that the assertion cannot be verified.  Inconclusive(String) : Indicates that the assertion cannot be verified & display a message  AreEqual(Object, Object)  AreNotEqual(Object, Object)  AreNotSame(Object, Object) :Ref comparison  IsTrue(Boolean)  IsFalse(Boolean)  IsNull(Object)  IsNotNull(Object)
    35. 35. Appendix – Test Attributes35  Unit Test Framework => Attributes  [TestClass()] : identify class that contains Test method  [TestMethod()] : identify Test method  [TestInitialize()] : identifies method that will be run before each test  [TestCleanup()] : identifies method that will be run after each test  [ExpectedException(exceptionType)] : Indicates that an exception is expected during test method execution. (The test method will pass if the expected exception is thrown.) See “Microsoft.VisualStudio.TestTools.UnitTesting Namespace” for list of attributes http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting(v=vs.100).aspx
    36. 36. References36  Microsoft (VS 2010): Walkthrough: Creating and Running Unit Tests  http://msdn.microsoft.com/en-us/library/ms182532(v=vs.100).aspx  Microsoft (VS 2010) : Walkthrough: Run Tests and View Code Coverage  http://msdn.microsoft.com/en-us/library/ms182534(v=vs.100).aspx  Microsoft (VS 2008) : Walkthrough: Working with Unit Tests  http://msdn.microsoft.com/en-us/library/ms182515(v=vs.90).aspx  Microsoft (VS 2008) : Guidelines for Test-Driven Development  http://msdn.microsoft.com/en-US/library/aa730844(v=VS.80).aspx
    1. A particular slide catching your eye?

      Clipping is a handy way to collect important slides you want to go back to later.