SlideShare ist ein Scribd-Unternehmen logo
1 von 24
Unit Testing in .net
Technical reasons
 Tests encourage better design sooner
 Tests are the best documentation
 Tests are your safety net
 Every day use
 Major refactoring freedom
Test Types
 Unit Testing
 Tests an atomic unit of code, such as a method
 Integration Testing
 Tests two or more software modules as a group
 User Acceptance Testing
 Tests performed by end users to validate specific features
 TDD Test
 Look like a unit test, feels like an user acceptance test
Unit Testing Defined
 A unit test is a piece of code that invokes the
method or class being tested and then checks
some assumptions about the logical behavior of
that method or class. A unit test is almost always
written using a unit-testing framework.
The Art of Unit Testing by Roy Osherove
Unit vs. Integration Testing
 Unit tests exercise and test a single
piece of code
 Integration tests exercise and test many
units of code that work together as a
whole
Code to Unit Test
 Unit tests should target logical code
 Logical code is defined as any piece of code
that contains any type of decision making
logic such as IF statements, loops, switch
statements, calculations etc.
Properties of a Good Unit Test
 It is Automated and Repeatable
 It is Easy to Implement
 It Can Be Run in the Future
 It Can Be Run by Anyone
 It Can Run at the Push of a Button
 It Runs Quickly
Test Project Creation Guidelines
 Demo and setup
Test Project Creation Guidelines
 Create separate test projects for unit tests and
integration tests. This will allow for calling unit
tests from the build process in the future
 Test project naming convention:
 [Project Name].UnitTests
 [Project Name].IntegrationTests
Test Class Guidelines
 Each class being tested should have its own test
class defined (the one-test-class-per-class pattern)
 Create utility methods if multiple tests need the same
functionality
 Test class naming convention:
 [Class Name]Tests.cs
where Class Name is the name of the class being
tested.
Test Method Guidelines
 Each public method exposed by the class under
test should be tested
// Configure/Setup
// Action
// Assert
Note: you can test Internal methods (if required). Use
InternalsVisibleTo[<Project>.UnitTests] attribute in AssemblyInfo.
 Test method naming convention:
 [Method Name]_[Scenario]_[ExpectedBehavior]
Examples:
ValidateCreditCard_InvalidExpiryDate_ThrowsException()
ValidateCreditCard_InvalidAddress_ThrowsException()
NUNIT Test Framework Attributes
Define class as a TestClass
[TestFixture]
public class FileManagerTests { }
Define a test method test a single method and expected
behavior
[Test]
public void IsValidFileName_InvalidFilePath_ThrowException(){ }
Use setup attribute to call required code before each test in the
class. For e.g. InitializeConfiguration()
Test Project Structure
 The test project, class, and method guidelines
allow us to do the following:
 Look at a project and find all related tests
 Look at a class and find all related tests
 Look at a class method and find all related tests
Unit Testing Techniques
 An external dependency is an object in the
system under test over which you have no
control.
 External dependencies need to be “faked”. It is
necessary to fake those dependencies to make
sure the scope of the code being tested is
limited to the system under test.
Unit Testing Techniques
 Stub:
 A controllable replacement for an existing external dependency in the
system.
 It allows to test code without dealing with dependencies directly, since
those dependencies are effectively simulated.
 can never fail a test
 Mock:
 A fake object in the system that decides whether the unit test passed or
failed.
 The unit test verifies the state of the mock object to determine success or
failure.
 may result in failed tests.
 State of the object would be checked as asserts gets created against
them.
.. And Dependency injection
 Decouple the components by injecting
them via constructors.
 Increase the testability.
Mocks and Stubs – Things to Consider
 Writing mocks and stubs takes time, so keep
them as simple as possible
 Focus on Reusability
 Inject stub/mocks to replace the dependency
component.
 Use available libraries e.g. RhinoMocks
Test Code Coverage
 Above 95% code coverage
 Do not confuse with covering entire assembly .
 Method level would be sufficient
 Use tools(Inbuilt or third party).
Hallmarks of Quality Tests
 Trustworthiness – Developers will want to run
trustworthy tests, which are tests whose results
are reliable
 Maintainability – Non-maintainable tests are
short-lived. The more focused and short the test
methods, the more maintainable.
 Readability - If the tests are not easily
readable, they will most likely be less
trustworthy and less maintainable
Signs of Trustworthy Tests
 When a test passes, your first reaction is not to
say “I’ll step through the debugger just to
make sure”
 When a test fails, your first reaction is not to
say, “Well, that does not mean the code is
not working”
 When you run the tests, your first reaction is not
to say “Yes but, what about this scenario?”
due to lack of coverage
Why UnitTests?
 Saves your time of debugging via print
statements, traces or VS debugger.
 Saves other’s time from stepping
through your code to ensure it’s working.
 Reduce bugs in early stage
 Better design
Resources
 Nunit
 http://www.nunit.org
 Code Coverage Overview
 http://msdn.microsoft.com/en-
us/library/cc667391(v=VS.90).aspx
 Rhino Mocks
 http://ayende.com/blog/tags/rhino-mocks
 Blog – www.cshandler.com
About me
Amit Choudhary
Microsoft MVP Visual C#
Twitter – @vendettamit

Weitere ähnliche Inhalte

Was ist angesagt?

Test driven development in .Net - 2010 + Eclipse
Test driven development in .Net - 2010 + EclipseTest driven development in .Net - 2010 + Eclipse
Test driven development in .Net - 2010 + EclipseUTC Fire & Security
 
.Net Unit Testing with Visual Studio 2010
.Net Unit Testing with Visual Studio 2010.Net Unit Testing with Visual Studio 2010
.Net Unit Testing with Visual Studio 2010kgayda
 
Unit tests & TDD
Unit tests & TDDUnit tests & TDD
Unit tests & TDDDror Helper
 
Unit Test Presentation
Unit Test PresentationUnit Test Presentation
Unit Test PresentationSayedur Rahman
 
Unit Testing Fundamentals
Unit Testing FundamentalsUnit Testing Fundamentals
Unit Testing FundamentalsRichard Paul
 
Introduction to testing with MSTest, Visual Studio, and Team Foundation Serve...
Introduction to testing with MSTest, Visual Studio, and Team Foundation Serve...Introduction to testing with MSTest, Visual Studio, and Team Foundation Serve...
Introduction to testing with MSTest, Visual Studio, and Team Foundation Serve...Thomas Weller
 
Roy Osherove on Unit Testing Good Practices and Horrible Mistakes
Roy Osherove on Unit Testing Good Practices and Horrible MistakesRoy Osherove on Unit Testing Good Practices and Horrible Mistakes
Roy Osherove on Unit Testing Good Practices and Horrible MistakesRoy Osherove
 
Unit Testing Guidelines
Unit Testing GuidelinesUnit Testing Guidelines
Unit Testing GuidelinesJoel Hooks
 
Understanding Unit Testing
Understanding Unit TestingUnderstanding Unit Testing
Understanding Unit Testingikhwanhayat
 
Test-Driven Development
Test-Driven DevelopmentTest-Driven Development
Test-Driven DevelopmentMeilan Ou
 
Unit Tests And Automated Testing
Unit Tests And Automated TestingUnit Tests And Automated Testing
Unit Tests And Automated TestingLee Englestone
 
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 and integration Testing
Unit and integration TestingUnit and integration Testing
Unit and integration TestingDavid Berliner
 
Mock driven development using .NET
Mock driven development using .NETMock driven development using .NET
Mock driven development using .NETPuneet Ghanshani
 

Was ist angesagt? (20)

Test driven development in .Net - 2010 + Eclipse
Test driven development in .Net - 2010 + EclipseTest driven development in .Net - 2010 + Eclipse
Test driven development in .Net - 2010 + Eclipse
 
.Net Unit Testing with Visual Studio 2010
.Net Unit Testing with Visual Studio 2010.Net Unit Testing with Visual Studio 2010
.Net Unit Testing with Visual Studio 2010
 
Unit testing
Unit testingUnit testing
Unit testing
 
Unit tests & TDD
Unit tests & TDDUnit tests & TDD
Unit tests & TDD
 
Unit Test Presentation
Unit Test PresentationUnit Test Presentation
Unit Test Presentation
 
Unit Testing Fundamentals
Unit Testing FundamentalsUnit Testing Fundamentals
Unit Testing Fundamentals
 
Introduction to testing with MSTest, Visual Studio, and Team Foundation Serve...
Introduction to testing with MSTest, Visual Studio, and Team Foundation Serve...Introduction to testing with MSTest, Visual Studio, and Team Foundation Serve...
Introduction to testing with MSTest, Visual Studio, and Team Foundation Serve...
 
Roy Osherove on Unit Testing Good Practices and Horrible Mistakes
Roy Osherove on Unit Testing Good Practices and Horrible MistakesRoy Osherove on Unit Testing Good Practices and Horrible Mistakes
Roy Osherove on Unit Testing Good Practices and Horrible Mistakes
 
Unit Testing Guidelines
Unit Testing GuidelinesUnit Testing Guidelines
Unit Testing Guidelines
 
Understanding Unit Testing
Understanding Unit TestingUnderstanding Unit Testing
Understanding Unit Testing
 
Test-Driven Development
Test-Driven DevelopmentTest-Driven Development
Test-Driven Development
 
Unit testing
Unit testingUnit testing
Unit testing
 
Unit Tests And Automated Testing
Unit Tests And Automated TestingUnit Tests And Automated Testing
Unit Tests And Automated Testing
 
Unit Testing
Unit TestingUnit Testing
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
 
Unit and integration Testing
Unit and integration TestingUnit and integration Testing
Unit and integration Testing
 
Best practices unit testing
Best practices unit testing Best practices unit testing
Best practices unit testing
 
Mock driven development using .NET
Mock driven development using .NETMock driven development using .NET
Mock driven development using .NET
 
Unit testing
Unit testingUnit testing
Unit testing
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 

Andere mochten auch

10 Insightful Quotes On Designing A Better Customer Experience
10 Insightful Quotes On Designing A Better Customer Experience10 Insightful Quotes On Designing A Better Customer Experience
10 Insightful Quotes On Designing A Better Customer ExperienceYuan Wang
 
Learn BEM: CSS Naming Convention
Learn BEM: CSS Naming ConventionLearn BEM: CSS Naming Convention
Learn BEM: CSS Naming ConventionIn a Rocket
 
How to Build a Dynamic Social Media Plan
How to Build a Dynamic Social Media PlanHow to Build a Dynamic Social Media Plan
How to Build a Dynamic Social Media PlanPost Planner
 
Lightning Talk #9: How UX and Data Storytelling Can Shape Policy by Mika Aldaba
Lightning Talk #9: How UX and Data Storytelling Can Shape Policy by Mika AldabaLightning Talk #9: How UX and Data Storytelling Can Shape Policy by Mika Aldaba
Lightning Talk #9: How UX and Data Storytelling Can Shape Policy by Mika Aldabaux singapore
 
SEO: Getting Personal
SEO: Getting PersonalSEO: Getting Personal
SEO: Getting PersonalKirsty Hulse
 

Andere mochten auch (7)

Resharper
ResharperResharper
Resharper
 
10 Insightful Quotes On Designing A Better Customer Experience
10 Insightful Quotes On Designing A Better Customer Experience10 Insightful Quotes On Designing A Better Customer Experience
10 Insightful Quotes On Designing A Better Customer Experience
 
Learn BEM: CSS Naming Convention
Learn BEM: CSS Naming ConventionLearn BEM: CSS Naming Convention
Learn BEM: CSS Naming Convention
 
How to Build a Dynamic Social Media Plan
How to Build a Dynamic Social Media PlanHow to Build a Dynamic Social Media Plan
How to Build a Dynamic Social Media Plan
 
Lightning Talk #9: How UX and Data Storytelling Can Shape Policy by Mika Aldaba
Lightning Talk #9: How UX and Data Storytelling Can Shape Policy by Mika AldabaLightning Talk #9: How UX and Data Storytelling Can Shape Policy by Mika Aldaba
Lightning Talk #9: How UX and Data Storytelling Can Shape Policy by Mika Aldaba
 
SEO: Getting Personal
SEO: Getting PersonalSEO: Getting Personal
SEO: Getting Personal
 
Succession “Losers”: What Happens to Executives Passed Over for the CEO Job?
Succession “Losers”: What Happens to Executives Passed Over for the CEO Job? Succession “Losers”: What Happens to Executives Passed Over for the CEO Job?
Succession “Losers”: What Happens to Executives Passed Over for the CEO Job?
 

Ähnlich wie Unit testing basics with NUnit and Visual Studio

Unit testing & TDD concepts with best practice guidelines.
Unit testing & TDD concepts with best practice guidelines.Unit testing & TDD concepts with best practice guidelines.
Unit testing & TDD concepts with best practice guidelines.Mohamed Taman
 
Peter Zimmerer - Passion For Testing, By Examples - EuroSTAR 2010
Peter Zimmerer - Passion For Testing, By Examples - EuroSTAR 2010Peter Zimmerer - Passion For Testing, By Examples - EuroSTAR 2010
Peter Zimmerer - Passion For Testing, By Examples - EuroSTAR 2010TEST Huddle
 
types of testing with descriptions and examples
types of testing with descriptions and examplestypes of testing with descriptions and examples
types of testing with descriptions and examplesMani Deepak Choudhry
 
Unit Testing & TDD Training for Mobile Apps
Unit Testing & TDD Training for Mobile AppsUnit Testing & TDD Training for Mobile Apps
Unit Testing & TDD Training for Mobile AppsMarcelo Busico
 
UNIT TESTING PPT
UNIT TESTING PPTUNIT TESTING PPT
UNIT TESTING PPTsuhasreddy1
 
03 test specification and execution
03   test specification and execution03   test specification and execution
03 test specification and executionClemens Reijnen
 
An introduction to unit testing
An introduction to unit testingAn introduction to unit testing
An introduction to unit testingAdam Stephensen
 
Object Oriented Testing
Object Oriented TestingObject Oriented Testing
Object Oriented TestingAMITJain879
 
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
 

Ähnlich wie Unit testing basics with NUnit and Visual Studio (20)

Unit testing & TDD concepts with best practice guidelines.
Unit testing & TDD concepts with best practice guidelines.Unit testing & TDD concepts with best practice guidelines.
Unit testing & TDD concepts with best practice guidelines.
 
Unit testing, principles
Unit testing, principlesUnit testing, principles
Unit testing, principles
 
Peter Zimmerer - Passion For Testing, By Examples - EuroSTAR 2010
Peter Zimmerer - Passion For Testing, By Examples - EuroSTAR 2010Peter Zimmerer - Passion For Testing, By Examples - EuroSTAR 2010
Peter Zimmerer - Passion For Testing, By Examples - EuroSTAR 2010
 
types of testing with descriptions and examples
types of testing with descriptions and examplestypes of testing with descriptions and examples
types of testing with descriptions and examples
 
Unit Testing & TDD Training for Mobile Apps
Unit Testing & TDD Training for Mobile AppsUnit Testing & TDD Training for Mobile Apps
Unit Testing & TDD Training for Mobile Apps
 
Unit Testing in Java
Unit Testing in JavaUnit Testing in Java
Unit Testing in Java
 
Unit tests and TDD
Unit tests and TDDUnit tests and TDD
Unit tests and TDD
 
QA process Presentation
QA process PresentationQA process Presentation
QA process Presentation
 
UNIT TESTING PPT
UNIT TESTING PPTUNIT TESTING PPT
UNIT TESTING PPT
 
03 test specification and execution
03   test specification and execution03   test specification and execution
03 test specification and execution
 
Effective unit testing
Effective unit testingEffective unit testing
Effective unit testing
 
An introduction to unit testing
An introduction to unit testingAn introduction to unit testing
An introduction to unit testing
 
Object Oriented Testing
Object Oriented TestingObject Oriented Testing
Object Oriented Testing
 
Ch13
Ch13Ch13
Ch13
 
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
 
Paper Ps
Paper PsPaper Ps
Paper Ps
 
upload ppt by browse button
upload ppt by browse buttonupload ppt by browse button
upload ppt by browse button
 

Kürzlich hochgeladen

Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfOverkill Security
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 

Kürzlich hochgeladen (20)

Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 

Unit testing basics with NUnit and Visual Studio

  • 2.
  • 3. Technical reasons  Tests encourage better design sooner  Tests are the best documentation  Tests are your safety net  Every day use  Major refactoring freedom
  • 4. Test Types  Unit Testing  Tests an atomic unit of code, such as a method  Integration Testing  Tests two or more software modules as a group  User Acceptance Testing  Tests performed by end users to validate specific features  TDD Test  Look like a unit test, feels like an user acceptance test
  • 5. Unit Testing Defined  A unit test is a piece of code that invokes the method or class being tested and then checks some assumptions about the logical behavior of that method or class. A unit test is almost always written using a unit-testing framework. The Art of Unit Testing by Roy Osherove
  • 6. Unit vs. Integration Testing  Unit tests exercise and test a single piece of code  Integration tests exercise and test many units of code that work together as a whole
  • 7. Code to Unit Test  Unit tests should target logical code  Logical code is defined as any piece of code that contains any type of decision making logic such as IF statements, loops, switch statements, calculations etc.
  • 8. Properties of a Good Unit Test  It is Automated and Repeatable  It is Easy to Implement  It Can Be Run in the Future  It Can Be Run by Anyone  It Can Run at the Push of a Button  It Runs Quickly
  • 9. Test Project Creation Guidelines  Demo and setup
  • 10. Test Project Creation Guidelines  Create separate test projects for unit tests and integration tests. This will allow for calling unit tests from the build process in the future  Test project naming convention:  [Project Name].UnitTests  [Project Name].IntegrationTests
  • 11. Test Class Guidelines  Each class being tested should have its own test class defined (the one-test-class-per-class pattern)  Create utility methods if multiple tests need the same functionality  Test class naming convention:  [Class Name]Tests.cs where Class Name is the name of the class being tested.
  • 12. Test Method Guidelines  Each public method exposed by the class under test should be tested // Configure/Setup // Action // Assert Note: you can test Internal methods (if required). Use InternalsVisibleTo[<Project>.UnitTests] attribute in AssemblyInfo.  Test method naming convention:  [Method Name]_[Scenario]_[ExpectedBehavior] Examples: ValidateCreditCard_InvalidExpiryDate_ThrowsException() ValidateCreditCard_InvalidAddress_ThrowsException()
  • 13. NUNIT Test Framework Attributes Define class as a TestClass [TestFixture] public class FileManagerTests { } Define a test method test a single method and expected behavior [Test] public void IsValidFileName_InvalidFilePath_ThrowException(){ } Use setup attribute to call required code before each test in the class. For e.g. InitializeConfiguration()
  • 14. Test Project Structure  The test project, class, and method guidelines allow us to do the following:  Look at a project and find all related tests  Look at a class and find all related tests  Look at a class method and find all related tests
  • 15. Unit Testing Techniques  An external dependency is an object in the system under test over which you have no control.  External dependencies need to be “faked”. It is necessary to fake those dependencies to make sure the scope of the code being tested is limited to the system under test.
  • 16. Unit Testing Techniques  Stub:  A controllable replacement for an existing external dependency in the system.  It allows to test code without dealing with dependencies directly, since those dependencies are effectively simulated.  can never fail a test  Mock:  A fake object in the system that decides whether the unit test passed or failed.  The unit test verifies the state of the mock object to determine success or failure.  may result in failed tests.  State of the object would be checked as asserts gets created against them.
  • 17. .. And Dependency injection  Decouple the components by injecting them via constructors.  Increase the testability.
  • 18. Mocks and Stubs – Things to Consider  Writing mocks and stubs takes time, so keep them as simple as possible  Focus on Reusability  Inject stub/mocks to replace the dependency component.  Use available libraries e.g. RhinoMocks
  • 19. Test Code Coverage  Above 95% code coverage  Do not confuse with covering entire assembly .  Method level would be sufficient  Use tools(Inbuilt or third party).
  • 20. Hallmarks of Quality Tests  Trustworthiness – Developers will want to run trustworthy tests, which are tests whose results are reliable  Maintainability – Non-maintainable tests are short-lived. The more focused and short the test methods, the more maintainable.  Readability - If the tests are not easily readable, they will most likely be less trustworthy and less maintainable
  • 21. Signs of Trustworthy Tests  When a test passes, your first reaction is not to say “I’ll step through the debugger just to make sure”  When a test fails, your first reaction is not to say, “Well, that does not mean the code is not working”  When you run the tests, your first reaction is not to say “Yes but, what about this scenario?” due to lack of coverage
  • 22. Why UnitTests?  Saves your time of debugging via print statements, traces or VS debugger.  Saves other’s time from stepping through your code to ensure it’s working.  Reduce bugs in early stage  Better design
  • 23. Resources  Nunit  http://www.nunit.org  Code Coverage Overview  http://msdn.microsoft.com/en- us/library/cc667391(v=VS.90).aspx  Rhino Mocks  http://ayende.com/blog/tags/rhino-mocks
  • 24.  Blog – www.cshandler.com About me Amit Choudhary Microsoft MVP Visual C# Twitter – @vendettamit

Hinweis der Redaktion

  1. Tests are the best documentationTests show how to call the method. Tests show the dependencies the methods depends upon. Tests show what the method is prepared to handle. Tests make your children smarter and your wife more beautiful.Tests are your safety netAs you write more production code, you will be assured that the new code does not break any legacy code. (Legacy Code: Code that works). When you write code with TDD, you will change cogitation of Legacy Code from negative to positive.
  2. we will be using Nunit as unit testing framework for this framework.
  3. Simple property getters and setters that contain no logic do not need to be unit tested.
  4. Examples of such dependencies are file systems, memory, time, threads, databases, web services etc.
  5. Spec Flowhttps://github.com/techtalk/SpecFlow/downloads