SlideShare une entreprise Scribd logo
1  sur  34
Télécharger pour lire hors ligne
An Introduction to Unit Test
       Using NUnit
           Wei Li
           08/2007
Test, Test and More Test
•   Developer Test
      o   Unit Test
      o   Integration Test
      o   Regression Test

•   QA Test
      o   Integration Test
      o   Regression Test
      o   Performance Test
      o   Stress Test

•   Customer/User Test
      o   Acceptability Test
      o   Useability Test
What Is Unit Test
• Self checking or validation to ensure your
  code works as expected

• Developer’s test

• Part of the construction cycle
Where Does Unit Test
           Sit In Life Cycle
• Requirement Gathering
• Business System Design
• Technical Design
   o Architecture Design
   o Technical System Design
• Construction
   o Code and Unit Test
• QA Test
• User Test
Unit Test Is Not
• QA test

• Customer/user test
Why Unit Test
• What? Write code to test code?

• Why?
Instant Feedback
• Unit test provides the earliest opportunity to
  identify and fix a defect
• The earlier a defect is caught, the less
  expensive it is to fix it
• Done before integration
• Like a dedicated QA/user sits next to you
  and test your code immediately
Help Design And Write Better
             Code
• If your code is hard to be unit tested, how
  can it be easily used, maintained and
  extended?
Regression Checker
• When new release of the external dependency
  comes, you can quickly run the unit tests to make
  certain the new release won’t break your system

• Automatic change detector
   – When changes are made to the code, automated unit
     tests ensure that the change does not break something
     somewhere
Good Way To Work On Legacy
           Code
• Write unit test to get started with legacy
  code
Good Way To Learn New
      Language and New API
• Write unit test cases to learn and try new
  API

• Your unit test cases become reusable
  knowledge base
Good For Reporting a Defect
• Write a test case to report a defect or bug in
  a system

• When something fails, writing a unit test for
  that failure guarantees that it's fixed for
  once and for all.
Save Time In Long Term
• Unit test is reusable and repeatable

• Unit test can be automated

• Write once run forever
There Is More Than One Way To
             Do It
• Main() method with lots of print out

• GUI “push that button” test

• Debugger test
Problems With The Above
              Methods
•   Is the test well structured?
•   Can it be automated?
•   Is the test repeatable?
•   Does it need human interaction?
•   Is it easy to be maintained ?
•   How to present test results?
Stop Debugger Test
• Debugger time is not recyclable

• Debugger session is not reusable by others

• Not a regression testing tool

• Mental assertion is error-prone and boring
Enter NUnit
• A unit test framework written in C#
• It uses attributes to identify unit test fixtures
• It uses assertions for verification
• It can be used to test any .NET code, not
  just C#
• It provides a console and GUI interface
• It can be integrated into VS.NET
How Does NUnit Test Code Look
            Like?
• Show me the code
NUnit Attributes
• Custom attribute injects more information
  to your class at compilation time

• NUnit uses it to mark and identify unit test
  fixture
NUnit Required Attributes
– [TestFixture]
   • Used to indicate that a class contains test methods


– [Test]
   • Used to indicate that a method within a test fixture
     should be run by the Test Runner application


Example: Test1.cs
NUnit Optional Attributes
– [SetUp]
   • Used to indicate a setup method should be ran before each of
     the tests

– [TearDown]
   • Used to indicate a tear down method should be ran after each
     of the tests are ran

Example: Test2.cs
NUnit Optional Attributes
– [TestFixtureSetUp]
    • Used to indicate a setup method that will be ran once; before
      all other tests. This is the first method that is called before the
      tests are started.

– [TestFixtureTearDown]
   • Used to indicate a tear down method that will be ran once;
     after all other tests have run. This is the last method that is
     called after all the tests have finished.


Example: Test3.cs
NUnit Optional Attributes
– [ExpectedException(typeof(Exception))]
    • When you want an exception to be thrown
    • Will only pass if exception type was thrown

– [Ignore(“Not ready yet")]

Example: Test4.cs
NUnit Assertion
• It is all unit test cares about

• NUnit provides a full set of assertions ready
  to be used

• Assertion failure means test failure
NUnit Assertion
•   Equality Asserts
•   Identity Asserts
•   Comparison Asserts
•   Type Asserts
•   Condition tests
•   Utility methods
NUnit Equal Assertion
• Assert.AreEqual(expected, real_value)
• Assert.AreEqual(expected, real_value,
  “a message”)

• Assert.AreNotEqual(expected, real_value)
• Assert.AreNotEqual(expected, real_value,
  “a message”)
NUnit Identity Assertion
• Assert.AreSame(expected, real_value)
• Assert.AreSame (expected, real_value,
  “a message”)

• Assert.AreNotSame (expected, real_value)
• Assert.AreNotSame (expected, real_value,
  “a message”)
NUnit Condition Assertion
•   Assert.IsTrue()
•   Assert.IsFalse()
•   Assert.IsNull()
•   Assert.IsNotNull()
•   Assert.IsEmpty()
•   Assert.IsNotEmpty()
Examples
Show me the code
Test Driven/Test First
               Development
•   Write a unit test case for a new functionality
•   Run the unit test and it will fail
•   Write just enough code to make the test pass
•   Run the unit test again and it passes
•   Refactory the code to make it better
•   Repeat the unit test
•   Repeat the cycle
Continuous Integration
• Get the latest version of the project from source
  control system
• Build/compile the code
• Run all unit test cases
• Publish the build and test results
• Notify the development team for any failure
• Repeat the process periodically, for example, once
  every hour
Continuous Integration
• Demo: using NAnt to build solution, run
  test cases, generate test result reports
Questions?
Happy Testing!

Contenu connexe

Tendances

automation testing benefits
automation testing benefitsautomation testing benefits
automation testing benefits
nazeer pasha
 

Tendances (20)

Automation Testing using Selenium
Automation Testing using SeleniumAutomation Testing using Selenium
Automation Testing using Selenium
 
Understanding Unit Testing
Understanding Unit TestingUnderstanding Unit Testing
Understanding Unit Testing
 
Selenium IDE LOCATORS
Selenium IDE LOCATORSSelenium IDE LOCATORS
Selenium IDE LOCATORS
 
Test Automation Framework Design | www.idexcel.com
Test Automation Framework Design | www.idexcel.comTest Automation Framework Design | www.idexcel.com
Test Automation Framework Design | www.idexcel.com
 
Junit
JunitJunit
Junit
 
Introduction to Test Automation
Introduction to Test AutomationIntroduction to Test Automation
Introduction to Test Automation
 
Unit tests & TDD
Unit tests & TDDUnit tests & TDD
Unit tests & TDD
 
Software Testing 101
Software Testing 101Software Testing 101
Software Testing 101
 
발표자료 1인qa로살아남는6가지방법
발표자료 1인qa로살아남는6가지방법발표자료 1인qa로살아남는6가지방법
발표자료 1인qa로살아남는6가지방법
 
Test automation
Test automationTest automation
Test automation
 
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
 
Manual testing
Manual testingManual testing
Manual testing
 
Java Unit Testing
Java Unit TestingJava Unit Testing
Java Unit Testing
 
automation testing benefits
automation testing benefitsautomation testing benefits
automation testing benefits
 
Integration testing
Integration testingIntegration testing
Integration testing
 
Automated Testing with Agile
Automated Testing with AgileAutomated Testing with Agile
Automated Testing with Agile
 
JUnit Presentation
JUnit PresentationJUnit Presentation
JUnit Presentation
 
Unit Testing Concepts and Best Practices
Unit Testing Concepts and Best PracticesUnit Testing Concepts and Best Practices
Unit Testing Concepts and Best Practices
 
Angular Unit Testing
Angular Unit TestingAngular Unit Testing
Angular Unit Testing
 
TestNG Framework
TestNG Framework TestNG Framework
TestNG Framework
 

En vedette

Comunicaciones katherine ltda
Comunicaciones katherine ltdaComunicaciones katherine ltda
Comunicaciones katherine ltda
katherinareyesq
 
Comunicaciones katherine ltda
Comunicaciones katherine ltdaComunicaciones katherine ltda
Comunicaciones katherine ltda
katherinareyesq
 
ми6 исследования в интернете2
ми6 исследования в интернете2ми6 исследования в интернете2
ми6 исследования в интернете2
Maria Yurkovskaya
 
Establecimientos comerciales de la manzana 3
Establecimientos comerciales de la manzana 3Establecimientos comerciales de la manzana 3
Establecimientos comerciales de la manzana 3
Cristian Sanchez
 

En vedette (20)

Unit testing with NUnit
Unit testing with NUnitUnit testing with NUnit
Unit testing with NUnit
 
NUnit Features Presentation
NUnit Features PresentationNUnit Features Presentation
NUnit Features Presentation
 
Nunit
NunitNunit
Nunit
 
How and what to unit test
How and what to unit testHow and what to unit test
How and what to unit test
 
Unit Testing (C#)
Unit Testing (C#)Unit Testing (C#)
Unit Testing (C#)
 
Introduction to Unit Testing
Introduction to Unit TestingIntroduction to Unit Testing
Introduction to Unit Testing
 
Unit Test Fun
Unit Test FunUnit Test Fun
Unit Test Fun
 
Nogaaa
NogaaaNogaaa
Nogaaa
 
Comunicaciones katherine ltda
Comunicaciones katherine ltdaComunicaciones katherine ltda
Comunicaciones katherine ltda
 
438lecture1
438lecture1438lecture1
438lecture1
 
Comunicaciones katherine ltda
Comunicaciones katherine ltdaComunicaciones katherine ltda
Comunicaciones katherine ltda
 
Prej Tregueseve të Teuhid-it
Prej Tregueseve të Teuhid-itPrej Tregueseve të Teuhid-it
Prej Tregueseve të Teuhid-it
 
ми6 исследования в интернете2
ми6 исследования в интернете2ми6 исследования в интернете2
ми6 исследования в интернете2
 
An introduction to the Spring Framework
An introduction to the Spring FrameworkAn introduction to the Spring Framework
An introduction to the Spring Framework
 
12th Kuala Lumpur Boys' Brigade Weekly Meeting
12th Kuala Lumpur Boys' Brigade Weekly Meeting12th Kuala Lumpur Boys' Brigade Weekly Meeting
12th Kuala Lumpur Boys' Brigade Weekly Meeting
 
JetBrains ReSharper
JetBrains ReSharperJetBrains ReSharper
JetBrains ReSharper
 
Establecimientos comerciales de la manzana 3
Establecimientos comerciales de la manzana 3Establecimientos comerciales de la manzana 3
Establecimientos comerciales de la manzana 3
 
Safe Creative qué hacemos y cómo lo hacemos
Safe Creative qué hacemos y cómo lo hacemosSafe Creative qué hacemos y cómo lo hacemos
Safe Creative qué hacemos y cómo lo hacemos
 
Estrategia de Desarrollo Local Participativo-AGUJAMA
Estrategia de Desarrollo Local Participativo-AGUJAMAEstrategia de Desarrollo Local Participativo-AGUJAMA
Estrategia de Desarrollo Local Participativo-AGUJAMA
 
Sequential file programming patterns and performance with .net
Sequential  file programming patterns and performance with .netSequential  file programming patterns and performance with .net
Sequential file programming patterns and performance with .net
 

Similaire à An Introduction to Unit Test Using NUnit

Similaire à An Introduction to Unit Test Using NUnit (20)

Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Automated testing overview
Automated testing overviewAutomated testing overview
Automated testing overview
 
Winning the battle against Automated testing
Winning the battle against Automated testingWinning the battle against Automated testing
Winning the battle against Automated testing
 
An Introduction to Unit Testing
An Introduction to Unit TestingAn Introduction to Unit Testing
An Introduction to Unit Testing
 
Week 14 Unit Testing.pptx
Week 14  Unit Testing.pptxWeek 14  Unit Testing.pptx
Week 14 Unit Testing.pptx
 
Testing Angular
Testing AngularTesting Angular
Testing Angular
 
Qt test framework
Qt test frameworkQt test framework
Qt test framework
 
Testing
TestingTesting
Testing
 
Agile Acceptance testing with Fitnesse
Agile Acceptance testing with FitnesseAgile Acceptance testing with Fitnesse
Agile Acceptance testing with Fitnesse
 
Database Unit Testing Made Easy with VSTS
Database Unit Testing Made Easy with VSTSDatabase Unit Testing Made Easy with VSTS
Database Unit Testing Made Easy with VSTS
 
Tdd
TddTdd
Tdd
 
Unit Testng with PHP Unit - A Step by Step Training
Unit Testng with PHP Unit - A Step by Step TrainingUnit Testng with PHP Unit - A Step by Step Training
Unit Testng with PHP Unit - A Step by Step Training
 
Istqb foundation level day 1
Istqb foundation level   day 1Istqb foundation level   day 1
Istqb foundation level day 1
 
Unit testing in PHP
Unit testing in PHPUnit testing in PHP
Unit testing in PHP
 
DIG1108C Lesson 7 Fall 2014
DIG1108C Lesson 7 Fall 2014DIG1108C Lesson 7 Fall 2014
DIG1108C Lesson 7 Fall 2014
 
Software testing
Software testingSoftware testing
Software testing
 
Software Testing
Software TestingSoftware Testing
Software Testing
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
Manual testing - Introduction to Manual Software testing
Manual testing - Introduction to Manual Software testingManual testing - Introduction to Manual Software testing
Manual testing - Introduction to Manual Software testing
 
Unit Tesing in iOS
Unit Tesing in iOSUnit Tesing in iOS
Unit Tesing in iOS
 

Dernier

Dernier (20)

TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
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...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
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
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 

An Introduction to Unit Test Using NUnit

  • 1. An Introduction to Unit Test Using NUnit Wei Li 08/2007
  • 2. Test, Test and More Test • Developer Test o Unit Test o Integration Test o Regression Test • QA Test o Integration Test o Regression Test o Performance Test o Stress Test • Customer/User Test o Acceptability Test o Useability Test
  • 3. What Is Unit Test • Self checking or validation to ensure your code works as expected • Developer’s test • Part of the construction cycle
  • 4. Where Does Unit Test Sit In Life Cycle • Requirement Gathering • Business System Design • Technical Design o Architecture Design o Technical System Design • Construction o Code and Unit Test • QA Test • User Test
  • 5. Unit Test Is Not • QA test • Customer/user test
  • 6. Why Unit Test • What? Write code to test code? • Why?
  • 7. Instant Feedback • Unit test provides the earliest opportunity to identify and fix a defect • The earlier a defect is caught, the less expensive it is to fix it • Done before integration • Like a dedicated QA/user sits next to you and test your code immediately
  • 8. Help Design And Write Better Code • If your code is hard to be unit tested, how can it be easily used, maintained and extended?
  • 9. Regression Checker • When new release of the external dependency comes, you can quickly run the unit tests to make certain the new release won’t break your system • Automatic change detector – When changes are made to the code, automated unit tests ensure that the change does not break something somewhere
  • 10. Good Way To Work On Legacy Code • Write unit test to get started with legacy code
  • 11. Good Way To Learn New Language and New API • Write unit test cases to learn and try new API • Your unit test cases become reusable knowledge base
  • 12. Good For Reporting a Defect • Write a test case to report a defect or bug in a system • When something fails, writing a unit test for that failure guarantees that it's fixed for once and for all.
  • 13. Save Time In Long Term • Unit test is reusable and repeatable • Unit test can be automated • Write once run forever
  • 14. There Is More Than One Way To Do It • Main() method with lots of print out • GUI “push that button” test • Debugger test
  • 15. Problems With The Above Methods • Is the test well structured? • Can it be automated? • Is the test repeatable? • Does it need human interaction? • Is it easy to be maintained ? • How to present test results?
  • 16. Stop Debugger Test • Debugger time is not recyclable • Debugger session is not reusable by others • Not a regression testing tool • Mental assertion is error-prone and boring
  • 17. Enter NUnit • A unit test framework written in C# • It uses attributes to identify unit test fixtures • It uses assertions for verification • It can be used to test any .NET code, not just C# • It provides a console and GUI interface • It can be integrated into VS.NET
  • 18. How Does NUnit Test Code Look Like? • Show me the code
  • 19. NUnit Attributes • Custom attribute injects more information to your class at compilation time • NUnit uses it to mark and identify unit test fixture
  • 20. NUnit Required Attributes – [TestFixture] • Used to indicate that a class contains test methods – [Test] • Used to indicate that a method within a test fixture should be run by the Test Runner application Example: Test1.cs
  • 21. NUnit Optional Attributes – [SetUp] • Used to indicate a setup method should be ran before each of the tests – [TearDown] • Used to indicate a tear down method should be ran after each of the tests are ran Example: Test2.cs
  • 22. NUnit Optional Attributes – [TestFixtureSetUp] • Used to indicate a setup method that will be ran once; before all other tests. This is the first method that is called before the tests are started. – [TestFixtureTearDown] • Used to indicate a tear down method that will be ran once; after all other tests have run. This is the last method that is called after all the tests have finished. Example: Test3.cs
  • 23. NUnit Optional Attributes – [ExpectedException(typeof(Exception))] • When you want an exception to be thrown • Will only pass if exception type was thrown – [Ignore(“Not ready yet")] Example: Test4.cs
  • 24. NUnit Assertion • It is all unit test cares about • NUnit provides a full set of assertions ready to be used • Assertion failure means test failure
  • 25. NUnit Assertion • Equality Asserts • Identity Asserts • Comparison Asserts • Type Asserts • Condition tests • Utility methods
  • 26. NUnit Equal Assertion • Assert.AreEqual(expected, real_value) • Assert.AreEqual(expected, real_value, “a message”) • Assert.AreNotEqual(expected, real_value) • Assert.AreNotEqual(expected, real_value, “a message”)
  • 27. NUnit Identity Assertion • Assert.AreSame(expected, real_value) • Assert.AreSame (expected, real_value, “a message”) • Assert.AreNotSame (expected, real_value) • Assert.AreNotSame (expected, real_value, “a message”)
  • 28. NUnit Condition Assertion • Assert.IsTrue() • Assert.IsFalse() • Assert.IsNull() • Assert.IsNotNull() • Assert.IsEmpty() • Assert.IsNotEmpty()
  • 30. Test Driven/Test First Development • Write a unit test case for a new functionality • Run the unit test and it will fail • Write just enough code to make the test pass • Run the unit test again and it passes • Refactory the code to make it better • Repeat the unit test • Repeat the cycle
  • 31. Continuous Integration • Get the latest version of the project from source control system • Build/compile the code • Run all unit test cases • Publish the build and test results • Notify the development team for any failure • Repeat the process periodically, for example, once every hour
  • 32. Continuous Integration • Demo: using NAnt to build solution, run test cases, generate test result reports