SlideShare a Scribd company logo
1 of 47
Using Visual Studio 2010
      By Karen Gayda
   The test project is created by selecting “New
    Project” from the File Menu.
   Expand Visual C# from the tree view on the
    left-hand side of the dialog.
   Select “Test” from the list of options.
   In the center pane, select “Test Project”.
   Give the project a name and add it to your
    application’s solution.
   Contains special classes designated by the
    [TestClass] attribute which are intended to run
    groups of tests.
   Generally speaking, each class in the application
    project will have a corresponding class in the unit
    test project.
   Some classes, such as UI classes, may not be tested
    by the Unit Test class for UI interactivity. This is
    tested with a macro-style test class type called a
    Coded UI Test.
   Non-UI methods/properties of a UI class can still
    be tested with a standard Unit Test class.
   Must have at least one test class in project.
   Project may have test data files for use by the
    unit tests.
   Project may have utility/helper classes for
    common functionality used by test classes and
    test methods.
   Project may use configuration files to setup
    state or provide environment information to
    the tests.
   Microsoft.VisualStudio.TestTools.UnitTesting
    namespace:
       The namespace has many classes to help you with your
        unit tests including:
       Assert classes that you can use to verify conditions in unit
        tests
       Initialization and cleanup attributes to run code before or
        after unit tests run to ensure a specific beginning and
        ending state
       The ExpectedException attribute to verify that a certain
        type of exception is thrown during unit test execution
       The TestContext class which stores information that is
        provided to unit tests such as data connection for data-
        driven tests and information that is required to run unit
        tests for ASP.NET Web Services
   TestClass attribute:
       When you create a unit test, the TestClass attribute is
        included in the test file to indicate that this particular
        class may contain methods marked with the
        [TestMethod()] attribute. Without the TestClass
        attribute, the test methods are ignored.
       A test class can inherit methods from another test
        class that is in the same assembly. This means that
        you can create test methods in a base test class and
        then use those methods in derived test classes.
   TestContext - When you create unit tests, a
    class private variable called
    testContextInstance is included for each test
    class. It is of type TestContext.
   The properties of the TestContext class store
    information about the currently running test
    class.
   ClassInitialize method
       Designated by the [ClassInitialize()] attribute.
       Used to setup anything needed by all the test
        methods that will be run in the class. Examples of
        this would be to create test databases, to create
        tables, to copy test files, etc.
       Takes TestContext variable as parameter.
       One class initialization method per unit test class.
   ClassCleanUp method
       Designated by the [ClassCleanUp()] attribute.
       Used to cleanup artifacts of the test class for the test
        run.
       Usually used to delete data, files, tables or databases
        created by the class.
       One class cleanup method per test class.
   TestInitialize method
       Designated by the [TestInitialize()] attribut.e
       Method that runs before the execution of every test
        in the class.
       Used to manage resources shared by the test
        methods in the class.
       Used to setup test environment to an
        initialized/known state prior to a test executing.
       One test initialize method per unit test class.
   TestCleanUp method
       Designated by the [TestCleanUp()] attribute
       Method runs after the execution of every test method
        in the unit test class.
       Used to return the test environment to a known state
        or clean up the artifacts created by a test.
       One test clean up method per unit test class.
   Designated by the [TestMethod] attribute.
   1 – n test methods per Unit Test class.
   1 method per major application requirement.
   1 method per public property/method/web
    method as well (in most cases).
   A test method should test a single requirement
    only.
   A test method should be atomic.
   IMPORTANT: Test methods must run
    independently of one another!!!
   Test methods can run in any order, therefore
    their operation cannot rely on state set by other
    test methods.
   Test methods expecting any state or
    environment setup should always have that set
    by ClassInitialze or TestInitialize.
   It is not recommended that any state be setup
    in the test method itself. Avoid doing so
    whenever possible.
   Test method names should clearly indicate the
    purpose of the test.
   For tests that test a public property/class
    method/web method, use the name with the
    word Test appended. An example of this
    would be “ConnectionStringTest”.
   For tests that test a specific requirement, use a
    clear requirement descriptor with the word
    Test appended to the end. An example of this
    would be “AllFilesProcessedTest”.
   Tests are deterministic.
   For a given environment state and known input
    value(s), an expected result is the outcome of an
    assertion.
   Hard-coded, expected values are normal/acceptable.
   Use the Assert class to check for various expected
    conditions/state such as equality, inequality, Boolean
    value, etc.
   Use the ExpectedException attribute of the test method
    to insure that a specific exception is thrown if the
    application should throw it for expected errors.
   If anyAssert method fails within a test, the test result
    will indicate failure.
   Unhandled exceptions are treated as failures
   Test methods can have information about resources
    they should use passed to them via attributes.
   The [DeploymentItem] attribute is used to specify
    deployment items such as a file or a directory to be
    used by a specific test.
   The [DeploymentItem] can also be applied to an entire
    test class.
   There can be multiple deployment items specified for a
    method or class.
   The [TestProperty] attribute is used to pass general
    name/value pair data to a test.
   Test methods can have multiple test property attributes
    specified.
   Best practice to have a good comment header for
    each test method to clearly indicate what is being
    tested.
   Should include the following:
      Purpose: Short description of aspect of application being
        tested.
      Prerequisites: Assumptions being made before test can run
        such as a database with certain data exists and is accessible to
        the test project.
      Test Data: Data being used and list of possible values or
        ranges.
      Steps: List of steps in test.
      Remarks: Any pertinent information about test not covered
        elsewhere but important to note.
   Usually created manually in test class by
    developer.
   Skeleton tests can be generated by Visual
    Studio for existing code.
   Generated tests can be created only for
    properties/methods in existing code classes or
    interfaces.
   Tests for specific requirements must be coded
    manually.
   There are several ways to add tests to a test
    project.
   To add a standard unit test class to your
    project, go to the “Test” main menu option of
    the VS 2010 IDE and select “New Test”
   Select the “Unit Test” item from the dialog box.
    (The other test types available in VS 2010 are
    not covered in this presentation).
   Give your test class a descriptive name and
    click OK.
   To add your own unit tests to class, add public
    void, parameterless methods decorated with
    the test method attribute.
   Any method decorated with the [TestMethod]
    attribute is considered a test by the unit testing
    framework if it is contained within a test class.
   Uncomment the initialize/cleanup methods in
    the region “Additional Test Attributes” if you
    wish to use and customize them for your test
    class.
   To generate tests from existing code, use the
    Unit Test Wizard.
   From the “Test” main menu option of the VS
    2010 IDE, select “New Test”.
   Select the “Unit Test Wizard” option.
   Select your unit test project from dropdown
    list.
   Click OK to run the wizard.
   Expand the namespaces for your application
    assembly in the tree view on the wizard.
   Expand the classes in the tree view to view the
    individual proprties/methods of the classes.
   Select the classes and/or methods for which you
    would like to generate unit tests.
   Click the settings button if you would like to
    modify the default code generation settings.
   Click the Add Assembly button if you want to
    generate tests from an additional assembly.
   Click OK to generate skeleton tests.
   Additional tests are easily added to existing
    test class from application project.
   Right-clicking from within your application
    class method gives context menu option to
    “Create unit test”.
   Wizard automatically selects current method in
    application (where cursor is positioned) and
    chooses the same target class in the test project
    as existing test methods for application class.
   The Test List Editor window is the easiest way
    to manually run tests from the Visual Studio
    2010 IDE.
   They can also be run from the command line in
    an automated fashion, from the Microsoft Test
    Manager application (both not covered in this
    presentation), from the Test Results window of
    the VS2010 IDE and from the Test View
    window of the VS 2010 IDE.
   From the “Test” main menu option of the VS
    2010 IDE, select “Windows”
   Choose the “Test List Editor” option
   The test list editor window gives you the
    ability to group, run and debug your tests and
    then view the results of the test run’s execution.
   Test results are displayed in the Test Results
    window.
   This window is automatically displayed by the
    Test List Editor when your test run completes
   All tests have a green “Passed” icon by them if
    the tests executed correctly
   Any test with a red “Failed” icon should be
    debugged to determine the reason for failure.
   Test result window displays a summary of all
    of the test results.
   Clicking an individual result in the results grid
    will open the results detail window and
    display more detailed information about the
    outcome of the selected test.
   Test Result Detail window provides detail
    error information if a test fails.
   Each test run creates a log of the results of the
    test run execution.
   Visual Studio will save the last 25 test runs by
    default.
   Different test runs can be viewed in the Test
    Results window.
   Test Results window will load most recent run
    by default.
   Select run name from dropdown at top of test
    results window to view other than most recent
    test run.
   Unit tests help with regression testing so that you
    may determine if new requirements/code changes
    have broken existing functionality in the code.
   The VS 2010 test framework includes a feature
    called Test Impact Analysis which helps to
    streamline regression testing.
   You can use Test Impact Analysis to record a
    baseline after initial unit test development.
   From then on, Test Impact Analysis will keep track
    of what tests need to be run after code changes to
    insure proper regression testing without running
    all of the tests.
   Visual Studio 2010 testing framework makes it
    easy to create and run unit tests for your Visual
    Studio 2010 projects.
   Good unit tests must follow industry standard
    best practices.
   Visual Studio does not impose any restrictions
    on what you put in your test.
   It is incumbent on the unit test creator to write
    good tests.
   http://msdn.microsoft.com/en-
    us/library/dd264975.aspx

   http://msdn.microsoft.com/en-
    us/library/ms182409

   http://blog.stevensanderson.com/2009/08/24/wr
    iting-great-unit-tests-best-and-worst-practises/

   http://en.wikipedia.org/wiki/Unit_testing
   http://www.softwaretestingstuff.com/2010/09/u
    nit-testing-best-practices-techniques.html

   http://www.amazon.com/dp/0321146530/?tag=s
    tackoverfl08-20

   http://msdn.microsoft.com/en-
    us/magazine/cc163665.aspx

   http://www.codeproject.com/Articles/10870/Ne
    w-Version-Of-Rhino-Mocks
   http://weblogs.asp.net/adilakhter/archive/2008/
    05/04/more-on-unit-testing-testcontext.aspx

   http://www.c-
    sharpcorner.com/uploadfile/dommym/a-test-
    driven-development-tutorial-in-C-Sharp-4-0/

   http://msdn.microsoft.com/en-
    us/vstudio/ff718185.aspx

   http://www.simple-talk.com/sql/t-sql-
    programming/close-these-loopholes---reproduce-
    database-errors/

More Related Content

What's hot (20)

Unit test
Unit testUnit test
Unit test
 
Beginners - Get Started With Unit Testing in .NET
Beginners - Get Started With Unit Testing in .NETBeginners - Get Started With Unit Testing in .NET
Beginners - Get Started With Unit Testing in .NET
 
Unit testing
Unit testingUnit testing
Unit testing
 
Unit testing with Junit
Unit testing with JunitUnit testing with Junit
Unit testing with Junit
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
Best practices unit testing
Best practices unit testing Best practices unit testing
Best practices unit testing
 
Testing In Java
Testing In JavaTesting In Java
Testing In Java
 
Clean Unit Test Patterns
Clean Unit Test PatternsClean Unit Test Patterns
Clean Unit Test Patterns
 
Unit Testing Concepts and Best Practices
Unit Testing Concepts and Best PracticesUnit Testing Concepts and Best Practices
Unit Testing Concepts and Best Practices
 
Junit 4.0
Junit 4.0Junit 4.0
Junit 4.0
 
Simple Unit Testing With Netbeans 6.1
Simple Unit Testing With Netbeans 6.1Simple Unit Testing With Netbeans 6.1
Simple Unit Testing With Netbeans 6.1
 
Unit Testing Fundamentals
Unit Testing FundamentalsUnit Testing Fundamentals
Unit Testing Fundamentals
 
JUnit Presentation
JUnit PresentationJUnit Presentation
JUnit Presentation
 
Unit Testing in Java
Unit Testing in JavaUnit Testing in Java
Unit Testing in Java
 
J Unit
J UnitJ Unit
J Unit
 
Testing and Mocking Object - The Art of Mocking.
Testing and Mocking Object - The Art of Mocking.Testing and Mocking Object - The Art of Mocking.
Testing and Mocking Object - The Art of Mocking.
 
Introduction To J unit
Introduction To J unitIntroduction To J unit
Introduction To J unit
 
Junit
JunitJunit
Junit
 
Java Unit Testing
Java Unit TestingJava Unit Testing
Java Unit Testing
 
Unit testing, principles
Unit testing, principlesUnit testing, principles
Unit testing, principles
 

Viewers also liked (20)

UNIT TESTING PPT
UNIT TESTING PPTUNIT TESTING PPT
UNIT TESTING PPT
 
Visual Studio IDE
Visual Studio IDEVisual Studio IDE
Visual Studio IDE
 
NUnit vs MSTest
NUnit vs MSTestNUnit vs MSTest
NUnit vs MSTest
 
RIA 06 & 07 - Unit Testing in Detail
RIA 06 & 07 - Unit Testing in DetailRIA 06 & 07 - Unit Testing in Detail
RIA 06 & 07 - Unit Testing in Detail
 
Becoming a better programmer - unit testing
Becoming a better programmer - unit testingBecoming a better programmer - unit testing
Becoming a better programmer - unit testing
 
Web and load testing with Visual Studio 2010 Ultimate
Web and load testing with Visual Studio 2010 UltimateWeb and load testing with Visual Studio 2010 Ultimate
Web and load testing with Visual Studio 2010 Ultimate
 
Life History of Building 3
Life History of Building 3Life History of Building 3
Life History of Building 3
 
Sahara Trust Hospital
Sahara Trust HospitalSahara Trust Hospital
Sahara Trust Hospital
 
Visual Studio
Visual StudioVisual Studio
Visual Studio
 
WordCamp US: Clean Code
WordCamp US: Clean CodeWordCamp US: Clean Code
WordCamp US: Clean Code
 
Presentation on Visual Studio
Presentation on Visual StudioPresentation on Visual Studio
Presentation on Visual Studio
 
Visual studio 2010
Visual studio 2010Visual studio 2010
Visual studio 2010
 
Visual studio 2010
Visual studio 2010Visual studio 2010
Visual studio 2010
 
Visual studio introduccion
Visual studio introduccionVisual studio introduccion
Visual studio introduccion
 
Activites and Time Planning
 Activites and Time Planning Activites and Time Planning
Activites and Time Planning
 
Visual studio 2010
Visual studio 2010Visual studio 2010
Visual studio 2010
 
Pert Estimating
Pert EstimatingPert Estimating
Pert Estimating
 
Office Automation System
Office Automation SystemOffice Automation System
Office Automation System
 
Chapter 2 — Program and Graphical User Interface Design
Chapter 2 — Program and Graphical User Interface DesignChapter 2 — Program and Graphical User Interface Design
Chapter 2 — Program and Graphical User Interface Design
 
Estimation
EstimationEstimation
Estimation
 

Similar to .Net Unit Testing with Visual Studio 2010

Unit testing and test driven development using vs
Unit testing and test driven development using vsUnit testing and test driven development using vs
Unit testing and test driven development using vsAbhimanyu Singhal
 
Unit testing basics with NUnit and Visual Studio
Unit testing basics with NUnit and Visual StudioUnit testing basics with NUnit and Visual Studio
Unit testing basics with NUnit and Visual StudioAmit Choudhary
 
Software Testing
Software TestingSoftware Testing
Software TestingKiran Kumar
 
TestNG - The Next Generation of Unit Testing
TestNG - The Next Generation of Unit TestingTestNG - The Next Generation of Unit Testing
TestNG - The Next Generation of Unit TestingBethmi Gunasekara
 
Unit testing and test driven development using vs
Unit testing and test driven development using vsUnit testing and test driven development using vs
Unit testing and test driven development using vsAbhimanyu Singhal
 
TestNG Session presented in PB
TestNG Session presented in PBTestNG Session presented in PB
TestNG Session presented in PBAbhishek Yadav
 
Tdd Ugialtnet Jan2010
Tdd Ugialtnet Jan2010Tdd Ugialtnet Jan2010
Tdd Ugialtnet Jan2010guestcff805
 
Chapter 3 SOFTWARE TESTING PROCESS
Chapter 3 SOFTWARE TESTING PROCESSChapter 3 SOFTWARE TESTING PROCESS
Chapter 3 SOFTWARE TESTING PROCESSst. michael
 
justin presentation upload PPT june 19
justin presentation upload PPT june 19justin presentation upload PPT june 19
justin presentation upload PPT june 19techweb08
 
justin for ppt1 by browse button
justin for ppt1 by browse buttonjustin for ppt1 by browse button
justin for ppt1 by browse buttontechweb08
 
upload ppt by browse button
upload ppt by browse buttonupload ppt by browse button
upload ppt by browse buttontechweb08
 
justin presentation Slideshare PPT upload June 25 Final one
justin presentation Slideshare PPT upload June 25 Final onejustin presentation Slideshare PPT upload June 25 Final one
justin presentation Slideshare PPT upload June 25 Final onetechweb08
 

Similar to .Net Unit Testing with Visual Studio 2010 (20)

Unit testing and test driven development using vs
Unit testing and test driven development using vsUnit testing and test driven development using vs
Unit testing and test driven development using vs
 
Unit testing basics with NUnit and Visual Studio
Unit testing basics with NUnit and Visual StudioUnit testing basics with NUnit and Visual Studio
Unit testing basics with NUnit and Visual Studio
 
Software Testing
Software TestingSoftware Testing
Software Testing
 
Ch23
Ch23Ch23
Ch23
 
TestNG - The Next Generation of Unit Testing
TestNG - The Next Generation of Unit TestingTestNG - The Next Generation of Unit Testing
TestNG - The Next Generation of Unit Testing
 
Unit testing and test driven development using vs
Unit testing and test driven development using vsUnit testing and test driven development using vs
Unit testing and test driven development using vs
 
Testing with Junit4
Testing with Junit4Testing with Junit4
Testing with Junit4
 
TestNG Session presented in PB
TestNG Session presented in PBTestNG Session presented in PB
TestNG Session presented in PB
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Tdd Ugialtnet Jan2010
Tdd Ugialtnet Jan2010Tdd Ugialtnet Jan2010
Tdd Ugialtnet Jan2010
 
Chapter 3 SOFTWARE TESTING PROCESS
Chapter 3 SOFTWARE TESTING PROCESSChapter 3 SOFTWARE TESTING PROCESS
Chapter 3 SOFTWARE TESTING PROCESS
 
Test ng for testers
Test ng for testersTest ng for testers
Test ng for testers
 
Junit
JunitJunit
Junit
 
unit 1 (1).pptx
unit 1 (1).pptxunit 1 (1).pptx
unit 1 (1).pptx
 
Paper CS
Paper CSPaper CS
Paper CS
 
alkatest7
alkatest7alkatest7
alkatest7
 
justin presentation upload PPT june 19
justin presentation upload PPT june 19justin presentation upload PPT june 19
justin presentation upload PPT june 19
 
justin for ppt1 by browse button
justin for ppt1 by browse buttonjustin for ppt1 by browse button
justin for ppt1 by browse button
 
upload ppt by browse button
upload ppt by browse buttonupload ppt by browse button
upload ppt by browse button
 
justin presentation Slideshare PPT upload June 25 Final one
justin presentation Slideshare PPT upload June 25 Final onejustin presentation Slideshare PPT upload June 25 Final one
justin presentation Slideshare PPT upload June 25 Final one
 

Recently uploaded

"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 

Recently uploaded (20)

"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 

.Net Unit Testing with Visual Studio 2010

  • 1. Using Visual Studio 2010 By Karen Gayda
  • 2. The test project is created by selecting “New Project” from the File Menu.  Expand Visual C# from the tree view on the left-hand side of the dialog.  Select “Test” from the list of options.  In the center pane, select “Test Project”.  Give the project a name and add it to your application’s solution.
  • 3.
  • 4. Contains special classes designated by the [TestClass] attribute which are intended to run groups of tests.  Generally speaking, each class in the application project will have a corresponding class in the unit test project.  Some classes, such as UI classes, may not be tested by the Unit Test class for UI interactivity. This is tested with a macro-style test class type called a Coded UI Test.  Non-UI methods/properties of a UI class can still be tested with a standard Unit Test class.
  • 5. Must have at least one test class in project.  Project may have test data files for use by the unit tests.  Project may have utility/helper classes for common functionality used by test classes and test methods.  Project may use configuration files to setup state or provide environment information to the tests.
  • 6.
  • 7. Microsoft.VisualStudio.TestTools.UnitTesting namespace:  The namespace has many classes to help you with your unit tests including:  Assert classes that you can use to verify conditions in unit tests  Initialization and cleanup attributes to run code before or after unit tests run to ensure a specific beginning and ending state  The ExpectedException attribute to verify that a certain type of exception is thrown during unit test execution  The TestContext class which stores information that is provided to unit tests such as data connection for data- driven tests and information that is required to run unit tests for ASP.NET Web Services
  • 8. TestClass attribute:  When you create a unit test, the TestClass attribute is included in the test file to indicate that this particular class may contain methods marked with the [TestMethod()] attribute. Without the TestClass attribute, the test methods are ignored.  A test class can inherit methods from another test class that is in the same assembly. This means that you can create test methods in a base test class and then use those methods in derived test classes.
  • 9. TestContext - When you create unit tests, a class private variable called testContextInstance is included for each test class. It is of type TestContext.  The properties of the TestContext class store information about the currently running test class.
  • 10.
  • 11. ClassInitialize method  Designated by the [ClassInitialize()] attribute.  Used to setup anything needed by all the test methods that will be run in the class. Examples of this would be to create test databases, to create tables, to copy test files, etc.  Takes TestContext variable as parameter.  One class initialization method per unit test class.
  • 12.
  • 13. ClassCleanUp method  Designated by the [ClassCleanUp()] attribute.  Used to cleanup artifacts of the test class for the test run.  Usually used to delete data, files, tables or databases created by the class.  One class cleanup method per test class.
  • 14.
  • 15. TestInitialize method  Designated by the [TestInitialize()] attribut.e  Method that runs before the execution of every test in the class.  Used to manage resources shared by the test methods in the class.  Used to setup test environment to an initialized/known state prior to a test executing.  One test initialize method per unit test class.
  • 16. TestCleanUp method  Designated by the [TestCleanUp()] attribute  Method runs after the execution of every test method in the unit test class.  Used to return the test environment to a known state or clean up the artifacts created by a test.  One test clean up method per unit test class.
  • 17. Designated by the [TestMethod] attribute.  1 – n test methods per Unit Test class.  1 method per major application requirement.  1 method per public property/method/web method as well (in most cases).  A test method should test a single requirement only.  A test method should be atomic.
  • 18. IMPORTANT: Test methods must run independently of one another!!!  Test methods can run in any order, therefore their operation cannot rely on state set by other test methods.  Test methods expecting any state or environment setup should always have that set by ClassInitialze or TestInitialize.  It is not recommended that any state be setup in the test method itself. Avoid doing so whenever possible.
  • 19. Test method names should clearly indicate the purpose of the test.  For tests that test a public property/class method/web method, use the name with the word Test appended. An example of this would be “ConnectionStringTest”.  For tests that test a specific requirement, use a clear requirement descriptor with the word Test appended to the end. An example of this would be “AllFilesProcessedTest”.
  • 20.
  • 21.
  • 22. Tests are deterministic.  For a given environment state and known input value(s), an expected result is the outcome of an assertion.  Hard-coded, expected values are normal/acceptable.  Use the Assert class to check for various expected conditions/state such as equality, inequality, Boolean value, etc.  Use the ExpectedException attribute of the test method to insure that a specific exception is thrown if the application should throw it for expected errors.  If anyAssert method fails within a test, the test result will indicate failure.  Unhandled exceptions are treated as failures
  • 23. Test methods can have information about resources they should use passed to them via attributes.  The [DeploymentItem] attribute is used to specify deployment items such as a file or a directory to be used by a specific test.  The [DeploymentItem] can also be applied to an entire test class.  There can be multiple deployment items specified for a method or class.  The [TestProperty] attribute is used to pass general name/value pair data to a test.  Test methods can have multiple test property attributes specified.
  • 24. Best practice to have a good comment header for each test method to clearly indicate what is being tested.  Should include the following: Purpose: Short description of aspect of application being tested. Prerequisites: Assumptions being made before test can run such as a database with certain data exists and is accessible to the test project. Test Data: Data being used and list of possible values or ranges. Steps: List of steps in test. Remarks: Any pertinent information about test not covered elsewhere but important to note.
  • 25. Usually created manually in test class by developer.  Skeleton tests can be generated by Visual Studio for existing code.  Generated tests can be created only for properties/methods in existing code classes or interfaces.  Tests for specific requirements must be coded manually.
  • 26. There are several ways to add tests to a test project.  To add a standard unit test class to your project, go to the “Test” main menu option of the VS 2010 IDE and select “New Test”  Select the “Unit Test” item from the dialog box. (The other test types available in VS 2010 are not covered in this presentation).  Give your test class a descriptive name and click OK.
  • 27.
  • 28.
  • 29. To add your own unit tests to class, add public void, parameterless methods decorated with the test method attribute.  Any method decorated with the [TestMethod] attribute is considered a test by the unit testing framework if it is contained within a test class.  Uncomment the initialize/cleanup methods in the region “Additional Test Attributes” if you wish to use and customize them for your test class.
  • 30. To generate tests from existing code, use the Unit Test Wizard.  From the “Test” main menu option of the VS 2010 IDE, select “New Test”.  Select the “Unit Test Wizard” option.  Select your unit test project from dropdown list.  Click OK to run the wizard.
  • 31.
  • 32. Expand the namespaces for your application assembly in the tree view on the wizard.  Expand the classes in the tree view to view the individual proprties/methods of the classes.  Select the classes and/or methods for which you would like to generate unit tests.  Click the settings button if you would like to modify the default code generation settings.  Click the Add Assembly button if you want to generate tests from an additional assembly.  Click OK to generate skeleton tests.
  • 33.
  • 34. Additional tests are easily added to existing test class from application project.  Right-clicking from within your application class method gives context menu option to “Create unit test”.  Wizard automatically selects current method in application (where cursor is positioned) and chooses the same target class in the test project as existing test methods for application class.
  • 35. The Test List Editor window is the easiest way to manually run tests from the Visual Studio 2010 IDE.  They can also be run from the command line in an automated fashion, from the Microsoft Test Manager application (both not covered in this presentation), from the Test Results window of the VS2010 IDE and from the Test View window of the VS 2010 IDE.
  • 36. From the “Test” main menu option of the VS 2010 IDE, select “Windows”  Choose the “Test List Editor” option  The test list editor window gives you the ability to group, run and debug your tests and then view the results of the test run’s execution.
  • 37.
  • 38. Test results are displayed in the Test Results window.  This window is automatically displayed by the Test List Editor when your test run completes  All tests have a green “Passed” icon by them if the tests executed correctly  Any test with a red “Failed” icon should be debugged to determine the reason for failure.
  • 39.
  • 40. Test result window displays a summary of all of the test results.  Clicking an individual result in the results grid will open the results detail window and display more detailed information about the outcome of the selected test.  Test Result Detail window provides detail error information if a test fails.
  • 41.
  • 42. Each test run creates a log of the results of the test run execution.  Visual Studio will save the last 25 test runs by default.  Different test runs can be viewed in the Test Results window.  Test Results window will load most recent run by default.  Select run name from dropdown at top of test results window to view other than most recent test run.
  • 43. Unit tests help with regression testing so that you may determine if new requirements/code changes have broken existing functionality in the code.  The VS 2010 test framework includes a feature called Test Impact Analysis which helps to streamline regression testing.  You can use Test Impact Analysis to record a baseline after initial unit test development.  From then on, Test Impact Analysis will keep track of what tests need to be run after code changes to insure proper regression testing without running all of the tests.
  • 44. Visual Studio 2010 testing framework makes it easy to create and run unit tests for your Visual Studio 2010 projects.  Good unit tests must follow industry standard best practices.  Visual Studio does not impose any restrictions on what you put in your test.  It is incumbent on the unit test creator to write good tests.
  • 45. http://msdn.microsoft.com/en- us/library/dd264975.aspx  http://msdn.microsoft.com/en- us/library/ms182409  http://blog.stevensanderson.com/2009/08/24/wr iting-great-unit-tests-best-and-worst-practises/  http://en.wikipedia.org/wiki/Unit_testing
  • 46. http://www.softwaretestingstuff.com/2010/09/u nit-testing-best-practices-techniques.html  http://www.amazon.com/dp/0321146530/?tag=s tackoverfl08-20  http://msdn.microsoft.com/en- us/magazine/cc163665.aspx  http://www.codeproject.com/Articles/10870/Ne w-Version-Of-Rhino-Mocks
  • 47. http://weblogs.asp.net/adilakhter/archive/2008/ 05/04/more-on-unit-testing-testcontext.aspx  http://www.c- sharpcorner.com/uploadfile/dommym/a-test- driven-development-tutorial-in-C-Sharp-4-0/  http://msdn.microsoft.com/en- us/vstudio/ff718185.aspx  http://www.simple-talk.com/sql/t-sql- programming/close-these-loopholes---reproduce- database-errors/

Editor's Notes

  1. This presentation is an introduction to unit testing using the Visual Studio 2010 testing framework. It covers the creation of unit tests and test projects, the structure of a standard Unit Test, unit test rules and best practices and the execution of unit test runs.
  2. This is the “New Project” dialog that is accessed from the IDE “File” menu. Here is where you add the Test Project to your application’s solution. To add the Test Project to your solution, you must select the “Test Project” template from the template list in the center of the dialog. Then you must give the project a name. The name of the application being tested with “Test” appended to it is a good naming convention to follow for your unit test projects. Choose a location at the same directory level or below your application directory. Be sure you choose “Add to Solution” on the solution line from the dropdown list.
  3. This is an example unit test project for an executable that is part of an ETL process. It contains test class files for each of the test classes in the application. It contains a folder, TestFiles, which contains data files for each of the test classes. Finally, it contains a utility class with common methods used by all of the unit test classes.You may or may not choose to follow this structure. It is not required or necessarily suited to your environment.
  4. Add the Microsoft.VisualStudio.TestTools.UnitTesting namespace with a using directive at the top of your unit test files.
  5. A unit test class must be marked with the [TestClass] attribute in order for tests within the class to be executed by the testing framework.
  6. Each unit test class must have a TestContext property that can be accessed by the test framework.
  7. Example of UnitTest class TestContext declaration section.
  8. Initialize methods are typically used to setup the test environment to a known state. ClassInitialize does this once before any of the test methods are run in the UnitTest class.
  9. ClassInitialize method. This example shows file directories used by tests being cleared, test files being copied, a test database being created and a test table being created. These are the types of tasks done in initialize methods. They bring the test environment into a known state so that the test results can be relied upon to be accurate.
  10. Cleanup methods are the counterparts to initialize methods. They handle any of the tasks that would need to be performed subsequent to test methods executing. The ClassCleanUp method executes after all of the test methods in the unit test class have run.
  11. ClassCleanUp method. This example shows test database being dropped after all tests in class have been executed.
  12. TestInitialize is run prior to each test method in the unit test class executing. This differs from the ClassInitialize in that it performs tasks that must be done before each of the tests is run rather than once before all of the tests are run.
  13. TestCleanUp is the counterpart to TestInitialize. This method will execute after each of the test methods in a unit test class.
  14. Example of tests that test public properties. Test names are the Property Name with the word Test appended to them.
  15. Examples of tests that test a specific requirement. The name of each test clearly indicates what the requirement is. Each method name is appended with the word Test.
  16. For more information about theMicrosoft.VisualStudio.TestTools.UnitTesting namespace see MSDN documentation found at:http://msdn.microsoft.com/en-us/library/ms244252http://msdn.microsoft.com/en-us/library/ms244252
  17. The add new test dialog. Choose the Unit Test item to add a standard unit test to your project.
  18. This is what a default unit test class skeleton looks like before you modify it with your code. It contains a class definition with the [TestClass] attribute. It also contains a definition for the TestContext class variable, commented initialize/cleanup methods and a sample test method skeleton called TestMethod1.
  19. The “Add New Test” dialog with Unit Test Wizard selected.
  20. Unit Test Wizard page that allows you to select what tests you wish to have generated.
  21. Adding tests when you create a new property or method in your code is easy. Place the cursor within the body of the property/method. Right-click the mouse to display the context menu. Choose the “Create Unit Tests” option. Accept the defaults Visual Studio provides. Click OK. The new skeleton method will be added to the class that corresponds to your application class.
  22. Test List Editor with tests grouped by Class Name for easiest viewing/selecting of tests to run. Green arrow on upper left of window is for running or debugging tests. Choose by clicking the little black down arrow to select whether you run or debug the tests that are checked in the test pane of the editor.You may create custom groups of tests to run. By doing this, you can avoid having to check/uncheck specific tests in left pane before executing them.
  23. Test Results window shows summary of test run. Test runs can be selected from dropdown list at top left of screen. Double-clicking on individual row will show detail window for individual test result.
  24. This window shows details of an individual test result. It is most useful when a test fails as it gives detailed error information.
  25. To learn more about the Visual Studio 2010 testing framework, general unit testing best practices, unit testing concepts and mastering features of the unit testing framework, see the links provided in the following three reference pages.