SlideShare a Scribd company logo
1 of 45
Download to read offline
Intro to Unit Testing
Module Overview
1. Why Tests Are Important
2. The Different Types of Tests
3. What is a Unit Test
4. Your First Unit Test - Hello World
5. What to Unit Test
6. Benefits of Unit Tests
7. What is *not* a Unit Test
Why are people writing unit tests?
 They need to prove they are smart
 They want to charge more
 They want to spend more time
coding before they ship
 They like more lines of code on
their stats
 They want to look good in
code reviews
 ?
 ?
Credit Card Validation (F5)
Credit Card Validation (with Unit Tests)
Save Time: Avoid Debuggerment
Whenever you are tempted to type something into a print statement or a debugger
expression, write it as a test instead. - Fowler
Pay a little now
or
Pay a lot later
Why are people writing unit tests?
Why Write Tests?
Why Tests Are Important
 Tests Reduce Bugs in New Features
 Tests Reduce Bugs in Existing Features
 Tests Are Great Documentation
 Tests Improve Design
 Testing Makes Development Faster
http://www.ssw.com.au/ssw/standards/rules/RulesToBetterUnitTests.aspx#WhyUnitTests
The Different Types of Tests
 Smoke Tests
 Unit Tests
 Integration Tests
 Functional / Acceptance Tests
 Load Tests
 Stress Tests
Do You Know the Different Types of
Tests
http://www.ssw.com.au/ssw/standards/rules/RulesToBetterUnitTes
ts.aspx#TypesOfTests
What is a Unit Test
Our First Unit Test
[TestMethod]
public void TestCalculation()
{
var orderManager = new OrderManager();
using (var db = new NorthwindDataContext())
{
var order = db.Orders.FirstOrDefault();
var actual = orderManager.GetTotalIncGST(order);
var expected = order.OrderItems.Sum(oi => oi.Qty * price) * 1.1;
Assert.AreEqual(actual, expected);
}
}
“A unit test is a fast, in-memory, consistent, automated and
repeatable test of a functional unit-of-work in the system.”
“A unit of work is any functional scenario in the system that contains
logic. It can be as short as a function, or it can span multiple
classes and functions, and it provides internal or business value to
the system under test.”
“Art of Unit Testing” Roy Osherove
What is a Unit test?
What makes something a UNIT test ?
Small: Validates a single concern / unit of work
Repeatable: You can rerun the same test as many times
as you want.
Consistent: Every time you run it, you get the same
result.
In Memory: It has no “hard” dependencies on anything
not in memory (such as file system, databases, network)
Fast: It should take a fraction of a second to run a unit test.
Readable
 Understand!
 What? Scenario? Expectation?
Maintainable
 We change our application
Trustworthy
 All  The code covered by unit tests works as expected
Attributes of a good Unit test
What is wrong with this test?
[TestMethod]
public void TestCalculation()
{
var orderManager = new OrderManager();
using (var db = new NorthwindDataContext())
{
var order = db.Orders.FirstOrDefault();
var actual = orderManager.GetTotalIncGST(order);
var expected = order.OrderItems.Sum(oi => oi.Qty * price) * 1.1;
Assert.AreEqual(actual, expected);
}
}
Hello Unit Tests – Your First Test
[TestClass]
public class StringValidationTests
{
[TestMethod]
public void IsValidEmailAddress_ForValidEmail_ReturnsTrue()
{
string email = "adam@stephensen.com";
bool result = email.IsValidEmailAddress();
Assert.IsTrue(result);
}
Let’s write a test
public static class StringValidation
{
public static bool IsValidEmailAddress(this string txtEmail)
{
return false;
}
Red
public static class StringValidation
{
public static bool IsValidEmailAddress(this string email)
{
Regex r = new Regex(@"^[w-]+(?:.[w-]+)*@(?:[w-]+.)+[a-zA-Z]{2,7}$");
Match match = r.Match(email);
return match.Success;
}
Green
[TestClass]
public class StringValidationTests_MSTest
{
[TestMethod]
public void IsValidEmailAddress_ForValidEmail_ReturnsTrue()
{
string email = "adam@stephensen.com";
bool result = email.IsValidEmailAddress();
Assert.IsTrue(result);
}
[TestMethod]
public void IsValidEmailAddress_ForEmailWithoutAmpersand_ReturnsFalse()
{
string email = "adamstephensen.com";
var result = email.IsValidEmailAddress();
Assert.IsFalse(result);
}
}
Test Both Ways
NUnit Test Fixtures
[TestFixture]
public class StringValidationTests_Nunit
{
[TestCase("adam@domain.com",Description="Valid simple email")]
[TestCase("adam-stephensen@domain-name.com", Description = "Valid email can contain hyphens")]
[TestCase("adam.stephensen.more@domain.com.au", Description = "Valid email with >1 periods")]
public void IsValidEmailAddress_ForValidEmails_ReturnsTrue(string email)
{
bool result = email.IsValidEmailAddress();
Assert.IsTrue(result);
}
[TestCase("adam@domain&more.com", Description = "Invalid email containing ampersand")]
[TestCase("@domain&other.com", Description = "Invalid email with no text before @")]
[TestCase("adam@", Description = "Invalid email with no text after @")]
[TestCase("adam@domain", Description = "Invalid email with no period after @")]
[TestCase("adam-domain.com", Description = "Email does not contain @")]
[TestCase("adam.@domain.com", Description = "Email cannot contain period directly before @")]
[TestCase("adam@.domain.com", Description = "Email cannot contain period directly after @")]
[TestCase(".adam@domain.com", Description = "Email cannot start with period")]
[TestCase("adam@domain.com.", Description = "Email cannot end with period")]
public void IsValidEmailAddress_ForInvalidEmail_ReturnsFalse(string email)
{
var result = email.IsValidEmailAddress();
Assert.IsFalse(result);
}
}
What to Unit Test
Do You Know What Code To Unit
Test?
Unit tests should be written for:
Fragile Code - e.g. Regular Expressions -
see below
When errors can be difficult to spot - e.g.
Rounding, arithmetic, calculations - see
below
Unit tests should not be written for:
Generated Code
Private methods
Dependencies - e.g. Database Schema,
Datasets, Web Services - see below
Performance - e.g. Slow forms, Time
critical applications - see below
http://www.ssw.com.au/ssw/standards/rules/RulesToBetterUnitTests.aspx#HowMany
Test Fragile Code
http://www.ssw.com.au/ssw/standards/rules/RulesToBetterUnitTests.aspx#RegEx
Tests for Complex Code
http://www.ssw.com.au/ssw/standards/rules/RulesToBetterUnitTests.aspx#Arithmetic
Tests are the Best Documentation
Static
Documentation is
Technical Debt !
Unit Tests add
value!
Test Your JavaScript
http://www.ssw.com.au/ssw/standards/rules/RulesToBetterUnitTests.aspx#TestJavascript
Benefits of Unit Tests
 Isolate each part of the program and check that the individual
parts work
 Strict, written contract that the piece of code must satisfy
 Allows you to refactor code and make sure it still works
correctly (regression testing)
Benefits of Unit Tests (1)
 Simplifies integration
 Testing the parts of a program first, and then testing their
integration
 Provides documentation
 Clients and other developers can look at their unit tests to gain
a basic understanding of the APIs and determine how to use
the module to fit their needs
 Improve code quality
 Code that cannot be easily tested is not factored properly
Benefits of Unit Tests (2)
 Code with automated validation reduces the time spent
manually testing, manually debugging, and hunting for errors
 Writing tests as the code is written lets you fail fast (find errors
early). Bugs are cheaper/faster to fix the earlier they are found
 Unit testing lets you refactor safely, finding any regressions as
they are introduced
Unit Tests Save Time
What is NOT a Unit Test
Pop Quiz – What’s NQR ?
[TestMethod]
public void TestCalculation()
{
var orderManager = new OrderManager();
using (var db = new NorthwindDataContext())
{
var order = db.Orders.FirstOrDefault();
var actual = orderManager.GetTotalIncGST(order);
var expected = order.OrderItems.Sum(oi => oi.Qty
* price) * 1.1;
Assert.AreEqual(actual, expected);
}
}
1. What are we testing?
2. Database Access !
It talks to the database
It communicates across the network
It touches the file system
It cannot be run in isolation from any other unit test
It can't run at the same time as any of your other unit tests
You have to do special things to your environment to run it
(e.g. editing config files / registry settings)
You are not testing a class in isolation from other concrete classes
When is a test *not* a Unit test?
http://www.ssw.com.au/ssw/standards/rules/RulesToBetterUnitTests.aspx#DependenciesDB
What is it ?
If it’s not a unit test…..
 Test the Integration of multiple components
 UI, Business Layer, Database
 Not in memory
 Touches
 File system
 Registry
 Database
 Other shared resources
Integration test
Run much slower
 not run in-memory
Less consistent
 Dependent from external resources
Has side effects
Harder to prepare
 E.g. Database setup
Integration test
Great when writing code to integrate to 3rd party APIs
Great for finding out when there is a problem with a large
complex system (is it the code, the database or a dependency)
Great for ensuring availability of external components
(zsValidate)
Integration test
Different Levels of Attention
Unit tests – should ALWAYS pass.
- Should be run on every CI Build
Integration tests – will sometimes be red
- Should be excluded from CI Build
Module Summary
1. Why Tests Are Important
2. The Different Types of Tests
3. What is a Unit Test
4. Your First Unit Test
5. What to Unit Test
6. Benefits of Unit Tests
7. What is NOT a Unit Test
Unit Testing References
 Roy Osherove
 Book http://www.artofunittesting.com/
 Blog http://weblogs.asp.net/ROsherove/
 Unit test definition
http://weblogs.asp.net/ROsherove/archive/2009/09/28/unit-test-definition-2-0.aspx
 Michael Feathers
 Blog http://www.artima.com/weblogs/index.jsp?blogger=mfeathers
 What is not a unit test? http://www.artima.com/weblogs/viewpost.jsp?thread=126923
 Unit Testing Rules
http://www.artima.com/weblogs/viewpost.jsp?thread=126923
 http://www.slideshare.net/nickokiss/unit-testing-best-practices
http://www.nickokiss.com/2009/09/unit-testing.html

More Related Content

What's hot

What's hot (20)

Unit testing best practices
Unit testing best practicesUnit testing best practices
Unit testing best practices
 
Unit and integration Testing
Unit and integration TestingUnit and integration Testing
Unit and integration Testing
 
Understanding Unit Testing
Understanding Unit TestingUnderstanding Unit Testing
Understanding Unit Testing
 
Unit testing
Unit testingUnit testing
Unit testing
 
Introduction & Manual Testing
Introduction & Manual TestingIntroduction & Manual Testing
Introduction & Manual Testing
 
Software Testing or Quality Assurance
Software Testing or Quality AssuranceSoftware Testing or Quality Assurance
Software Testing or Quality Assurance
 
05 junit
05 junit05 junit
05 junit
 
JUnit Presentation
JUnit PresentationJUnit Presentation
JUnit Presentation
 
TestNG Framework
TestNG Framework TestNG Framework
TestNG Framework
 
Unit testing
Unit testing Unit testing
Unit testing
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
Unit testing
Unit testingUnit testing
Unit testing
 
An Introduction to Unit Testing
An Introduction to Unit TestingAn Introduction to Unit Testing
An Introduction to Unit Testing
 
Unit Tests And Automated Testing
Unit Tests And Automated TestingUnit Tests And Automated Testing
Unit Tests And Automated Testing
 
Nunit
NunitNunit
Nunit
 
Integration testing
Integration testingIntegration testing
Integration testing
 
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
 
Software testing principles
Software testing principlesSoftware testing principles
Software testing principles
 
Workshop unit test
Workshop   unit testWorkshop   unit test
Workshop unit test
 
Automation Testing
Automation TestingAutomation Testing
Automation Testing
 

Similar to An introduction to unit testing

Google test training
Google test trainingGoogle test training
Google test trainingThierry Gayet
 
Automated Software Testing Framework Training by Quontra Solutions
Automated Software Testing Framework Training by Quontra SolutionsAutomated Software Testing Framework Training by Quontra Solutions
Automated Software Testing Framework Training by Quontra SolutionsQuontra Solutions
 
Unit testing php-unit - phing - selenium_v2
Unit testing   php-unit - phing - selenium_v2Unit testing   php-unit - phing - selenium_v2
Unit testing php-unit - phing - selenium_v2Tricode (part of Dept)
 
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
 
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
 
Unit & integration testing
Unit & integration testingUnit & integration testing
Unit & integration testingPavlo Hodysh
 
Lightning Talks by Globant - Automation (This app runs by itself )
Lightning Talks by Globant -  Automation (This app runs by itself ) Lightning Talks by Globant -  Automation (This app runs by itself )
Lightning Talks by Globant - Automation (This app runs by itself ) Globant
 
Testes? Mas isso não aumenta o tempo de projecto? Não quero...
Testes? Mas isso não aumenta o tempo de projecto? Não quero...Testes? Mas isso não aumenta o tempo de projecto? Não quero...
Testes? Mas isso não aumenta o tempo de projecto? Não quero...Comunidade NetPonto
 
Beyond Static Analysis: Integrating .NET Static Analysis with Unit Testing a...
Beyond Static Analysis: Integrating .NET  Static Analysis with Unit Testing a...Beyond Static Analysis: Integrating .NET  Static Analysis with Unit Testing a...
Beyond Static Analysis: Integrating .NET Static Analysis with Unit Testing a...Erika Barron
 
Oh so you test? - A guide to testing on Android from Unit to Mutation
Oh so you test? - A guide to testing on Android from Unit to MutationOh so you test? - A guide to testing on Android from Unit to Mutation
Oh so you test? - A guide to testing on Android from Unit to MutationPaul Blundell
 

Similar to An introduction to unit testing (20)

Google test training
Google test trainingGoogle test training
Google test training
 
TDD Workshop UTN 2012
TDD Workshop UTN 2012TDD Workshop UTN 2012
TDD Workshop UTN 2012
 
Testing 101
Testing 101Testing 101
Testing 101
 
TDD Best Practices
TDD Best PracticesTDD Best Practices
TDD Best Practices
 
Unit testing, principles
Unit testing, principlesUnit testing, principles
Unit testing, principles
 
Automated Software Testing Framework Training by Quontra Solutions
Automated Software Testing Framework Training by Quontra SolutionsAutomated Software Testing Framework Training by Quontra Solutions
Automated Software Testing Framework Training by Quontra Solutions
 
Unit testing php-unit - phing - selenium_v2
Unit testing   php-unit - phing - selenium_v2Unit testing   php-unit - phing - selenium_v2
Unit testing php-unit - phing - selenium_v2
 
Why Unit Testingl
Why Unit TestinglWhy Unit Testingl
Why Unit Testingl
 
Why unit testingl
Why unit testinglWhy unit testingl
Why unit testingl
 
Why Unit Testingl
Why Unit TestinglWhy Unit Testingl
Why Unit Testingl
 
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
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
Unit testing
Unit testingUnit testing
Unit testing
 
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 & integration testing
Unit & integration testingUnit & integration testing
Unit & integration testing
 
Lightning Talks by Globant - Automation (This app runs by itself )
Lightning Talks by Globant -  Automation (This app runs by itself ) Lightning Talks by Globant -  Automation (This app runs by itself )
Lightning Talks by Globant - Automation (This app runs by itself )
 
Testes? Mas isso não aumenta o tempo de projecto? Não quero...
Testes? Mas isso não aumenta o tempo de projecto? Não quero...Testes? Mas isso não aumenta o tempo de projecto? Não quero...
Testes? Mas isso não aumenta o tempo de projecto? Não quero...
 
Beyond Static Analysis: Integrating .NET Static Analysis with Unit Testing a...
Beyond Static Analysis: Integrating .NET  Static Analysis with Unit Testing a...Beyond Static Analysis: Integrating .NET  Static Analysis with Unit Testing a...
Beyond Static Analysis: Integrating .NET Static Analysis with Unit Testing a...
 
Software Testing 5/5
Software Testing 5/5Software Testing 5/5
Software Testing 5/5
 
Oh so you test? - A guide to testing on Android from Unit to Mutation
Oh so you test? - A guide to testing on Android from Unit to MutationOh so you test? - A guide to testing on Android from Unit to Mutation
Oh so you test? - A guide to testing on Android from Unit to Mutation
 

More from Adam Stephensen

App Modernisation with Microsoft Azure
App Modernisation with Microsoft AzureApp Modernisation with Microsoft Azure
App Modernisation with Microsoft AzureAdam Stephensen
 
2019 05 - Exploring Container Offerings in Azure
2019 05 - Exploring Container Offerings in Azure2019 05 - Exploring Container Offerings in Azure
2019 05 - Exploring Container Offerings in AzureAdam Stephensen
 
2019 04 Containers - The secret to shipping cloud workloads
2019 04 Containers - The secret to shipping cloud workloads 2019 04 Containers - The secret to shipping cloud workloads
2019 04 Containers - The secret to shipping cloud workloads Adam Stephensen
 
Agile & DevOps - It's all about project success
Agile & DevOps - It's all about project successAgile & DevOps - It's all about project success
Agile & DevOps - It's all about project successAdam Stephensen
 
NDC Sydney 2018 | Bots - the Next UI Revolution | Adam Stephensen
NDC Sydney 2018 | Bots - the Next UI Revolution | Adam StephensenNDC Sydney 2018 | Bots - the Next UI Revolution | Adam Stephensen
NDC Sydney 2018 | Bots - the Next UI Revolution | Adam StephensenAdam Stephensen
 
An Introduction to Enterprise Design Patterns
An Introduction to Enterprise Design PatternsAn Introduction to Enterprise Design Patterns
An Introduction to Enterprise Design PatternsAdam Stephensen
 
An Introduction to Dependency Injection
An Introduction to Dependency InjectionAn Introduction to Dependency Injection
An Introduction to Dependency InjectionAdam Stephensen
 

More from Adam Stephensen (8)

App Modernisation with Microsoft Azure
App Modernisation with Microsoft AzureApp Modernisation with Microsoft Azure
App Modernisation with Microsoft Azure
 
2019 05 - Exploring Container Offerings in Azure
2019 05 - Exploring Container Offerings in Azure2019 05 - Exploring Container Offerings in Azure
2019 05 - Exploring Container Offerings in Azure
 
2019 04 Containers - The secret to shipping cloud workloads
2019 04 Containers - The secret to shipping cloud workloads 2019 04 Containers - The secret to shipping cloud workloads
2019 04 Containers - The secret to shipping cloud workloads
 
Agile & DevOps - It's all about project success
Agile & DevOps - It's all about project successAgile & DevOps - It's all about project success
Agile & DevOps - It's all about project success
 
NDC Sydney 2018 | Bots - the Next UI Revolution | Adam Stephensen
NDC Sydney 2018 | Bots - the Next UI Revolution | Adam StephensenNDC Sydney 2018 | Bots - the Next UI Revolution | Adam Stephensen
NDC Sydney 2018 | Bots - the Next UI Revolution | Adam Stephensen
 
An Introduction to Enterprise Design Patterns
An Introduction to Enterprise Design PatternsAn Introduction to Enterprise Design Patterns
An Introduction to Enterprise Design Patterns
 
An Introduction to Dependency Injection
An Introduction to Dependency InjectionAn Introduction to Dependency Injection
An Introduction to Dependency Injection
 
SOLID Principles
SOLID PrinciplesSOLID Principles
SOLID Principles
 

Recently uploaded

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...apidays
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
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
 
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
 
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
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
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
 
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
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
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
 
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 TerraformAndrey Devyatkin
 

Recently uploaded (20)

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...
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.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...
 
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
 
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
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
+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...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
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...
 
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...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
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
 
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
 

An introduction to unit testing

  • 1. Intro to Unit Testing
  • 2. Module Overview 1. Why Tests Are Important 2. The Different Types of Tests 3. What is a Unit Test 4. Your First Unit Test - Hello World 5. What to Unit Test 6. Benefits of Unit Tests 7. What is *not* a Unit Test
  • 3. Why are people writing unit tests?  They need to prove they are smart  They want to charge more  They want to spend more time coding before they ship  They like more lines of code on their stats  They want to look good in code reviews  ?
  • 4.  ? Credit Card Validation (F5)
  • 5.
  • 6.
  • 7. Credit Card Validation (with Unit Tests)
  • 8. Save Time: Avoid Debuggerment Whenever you are tempted to type something into a print statement or a debugger expression, write it as a test instead. - Fowler
  • 9. Pay a little now or Pay a lot later Why are people writing unit tests?
  • 11. Why Tests Are Important  Tests Reduce Bugs in New Features  Tests Reduce Bugs in Existing Features  Tests Are Great Documentation  Tests Improve Design  Testing Makes Development Faster http://www.ssw.com.au/ssw/standards/rules/RulesToBetterUnitTests.aspx#WhyUnitTests
  • 13.  Smoke Tests  Unit Tests  Integration Tests  Functional / Acceptance Tests  Load Tests  Stress Tests Do You Know the Different Types of Tests http://www.ssw.com.au/ssw/standards/rules/RulesToBetterUnitTes ts.aspx#TypesOfTests
  • 14. What is a Unit Test
  • 15. Our First Unit Test [TestMethod] public void TestCalculation() { var orderManager = new OrderManager(); using (var db = new NorthwindDataContext()) { var order = db.Orders.FirstOrDefault(); var actual = orderManager.GetTotalIncGST(order); var expected = order.OrderItems.Sum(oi => oi.Qty * price) * 1.1; Assert.AreEqual(actual, expected); } }
  • 16. “A unit test is a fast, in-memory, consistent, automated and repeatable test of a functional unit-of-work in the system.” “A unit of work is any functional scenario in the system that contains logic. It can be as short as a function, or it can span multiple classes and functions, and it provides internal or business value to the system under test.” “Art of Unit Testing” Roy Osherove What is a Unit test?
  • 17. What makes something a UNIT test ? Small: Validates a single concern / unit of work Repeatable: You can rerun the same test as many times as you want. Consistent: Every time you run it, you get the same result. In Memory: It has no “hard” dependencies on anything not in memory (such as file system, databases, network) Fast: It should take a fraction of a second to run a unit test.
  • 18. Readable  Understand!  What? Scenario? Expectation? Maintainable  We change our application Trustworthy  All  The code covered by unit tests works as expected Attributes of a good Unit test
  • 19. What is wrong with this test? [TestMethod] public void TestCalculation() { var orderManager = new OrderManager(); using (var db = new NorthwindDataContext()) { var order = db.Orders.FirstOrDefault(); var actual = orderManager.GetTotalIncGST(order); var expected = order.OrderItems.Sum(oi => oi.Qty * price) * 1.1; Assert.AreEqual(actual, expected); } }
  • 20. Hello Unit Tests – Your First Test
  • 21. [TestClass] public class StringValidationTests { [TestMethod] public void IsValidEmailAddress_ForValidEmail_ReturnsTrue() { string email = "adam@stephensen.com"; bool result = email.IsValidEmailAddress(); Assert.IsTrue(result); } Let’s write a test
  • 22. public static class StringValidation { public static bool IsValidEmailAddress(this string txtEmail) { return false; } Red
  • 23. public static class StringValidation { public static bool IsValidEmailAddress(this string email) { Regex r = new Regex(@"^[w-]+(?:.[w-]+)*@(?:[w-]+.)+[a-zA-Z]{2,7}$"); Match match = r.Match(email); return match.Success; } Green
  • 24. [TestClass] public class StringValidationTests_MSTest { [TestMethod] public void IsValidEmailAddress_ForValidEmail_ReturnsTrue() { string email = "adam@stephensen.com"; bool result = email.IsValidEmailAddress(); Assert.IsTrue(result); } [TestMethod] public void IsValidEmailAddress_ForEmailWithoutAmpersand_ReturnsFalse() { string email = "adamstephensen.com"; var result = email.IsValidEmailAddress(); Assert.IsFalse(result); } } Test Both Ways
  • 25. NUnit Test Fixtures [TestFixture] public class StringValidationTests_Nunit { [TestCase("adam@domain.com",Description="Valid simple email")] [TestCase("adam-stephensen@domain-name.com", Description = "Valid email can contain hyphens")] [TestCase("adam.stephensen.more@domain.com.au", Description = "Valid email with >1 periods")] public void IsValidEmailAddress_ForValidEmails_ReturnsTrue(string email) { bool result = email.IsValidEmailAddress(); Assert.IsTrue(result); } [TestCase("adam@domain&more.com", Description = "Invalid email containing ampersand")] [TestCase("@domain&other.com", Description = "Invalid email with no text before @")] [TestCase("adam@", Description = "Invalid email with no text after @")] [TestCase("adam@domain", Description = "Invalid email with no period after @")] [TestCase("adam-domain.com", Description = "Email does not contain @")] [TestCase("adam.@domain.com", Description = "Email cannot contain period directly before @")] [TestCase("adam@.domain.com", Description = "Email cannot contain period directly after @")] [TestCase(".adam@domain.com", Description = "Email cannot start with period")] [TestCase("adam@domain.com.", Description = "Email cannot end with period")] public void IsValidEmailAddress_ForInvalidEmail_ReturnsFalse(string email) { var result = email.IsValidEmailAddress(); Assert.IsFalse(result); } }
  • 26. What to Unit Test
  • 27. Do You Know What Code To Unit Test? Unit tests should be written for: Fragile Code - e.g. Regular Expressions - see below When errors can be difficult to spot - e.g. Rounding, arithmetic, calculations - see below Unit tests should not be written for: Generated Code Private methods Dependencies - e.g. Database Schema, Datasets, Web Services - see below Performance - e.g. Slow forms, Time critical applications - see below http://www.ssw.com.au/ssw/standards/rules/RulesToBetterUnitTests.aspx#HowMany
  • 29. Tests for Complex Code http://www.ssw.com.au/ssw/standards/rules/RulesToBetterUnitTests.aspx#Arithmetic
  • 30. Tests are the Best Documentation Static Documentation is Technical Debt ! Unit Tests add value!
  • 33.  Isolate each part of the program and check that the individual parts work  Strict, written contract that the piece of code must satisfy  Allows you to refactor code and make sure it still works correctly (regression testing) Benefits of Unit Tests (1)
  • 34.  Simplifies integration  Testing the parts of a program first, and then testing their integration  Provides documentation  Clients and other developers can look at their unit tests to gain a basic understanding of the APIs and determine how to use the module to fit their needs  Improve code quality  Code that cannot be easily tested is not factored properly Benefits of Unit Tests (2)
  • 35.  Code with automated validation reduces the time spent manually testing, manually debugging, and hunting for errors  Writing tests as the code is written lets you fail fast (find errors early). Bugs are cheaper/faster to fix the earlier they are found  Unit testing lets you refactor safely, finding any regressions as they are introduced Unit Tests Save Time
  • 36. What is NOT a Unit Test
  • 37. Pop Quiz – What’s NQR ? [TestMethod] public void TestCalculation() { var orderManager = new OrderManager(); using (var db = new NorthwindDataContext()) { var order = db.Orders.FirstOrDefault(); var actual = orderManager.GetTotalIncGST(order); var expected = order.OrderItems.Sum(oi => oi.Qty * price) * 1.1; Assert.AreEqual(actual, expected); } } 1. What are we testing? 2. Database Access !
  • 38. It talks to the database It communicates across the network It touches the file system It cannot be run in isolation from any other unit test It can't run at the same time as any of your other unit tests You have to do special things to your environment to run it (e.g. editing config files / registry settings) You are not testing a class in isolation from other concrete classes When is a test *not* a Unit test? http://www.ssw.com.au/ssw/standards/rules/RulesToBetterUnitTests.aspx#DependenciesDB
  • 39. What is it ? If it’s not a unit test…..
  • 40.  Test the Integration of multiple components  UI, Business Layer, Database  Not in memory  Touches  File system  Registry  Database  Other shared resources Integration test
  • 41. Run much slower  not run in-memory Less consistent  Dependent from external resources Has side effects Harder to prepare  E.g. Database setup Integration test
  • 42. Great when writing code to integrate to 3rd party APIs Great for finding out when there is a problem with a large complex system (is it the code, the database or a dependency) Great for ensuring availability of external components (zsValidate) Integration test
  • 43. Different Levels of Attention Unit tests – should ALWAYS pass. - Should be run on every CI Build Integration tests – will sometimes be red - Should be excluded from CI Build
  • 44. Module Summary 1. Why Tests Are Important 2. The Different Types of Tests 3. What is a Unit Test 4. Your First Unit Test 5. What to Unit Test 6. Benefits of Unit Tests 7. What is NOT a Unit Test
  • 45. Unit Testing References  Roy Osherove  Book http://www.artofunittesting.com/  Blog http://weblogs.asp.net/ROsherove/  Unit test definition http://weblogs.asp.net/ROsherove/archive/2009/09/28/unit-test-definition-2-0.aspx  Michael Feathers  Blog http://www.artima.com/weblogs/index.jsp?blogger=mfeathers  What is not a unit test? http://www.artima.com/weblogs/viewpost.jsp?thread=126923  Unit Testing Rules http://www.artima.com/weblogs/viewpost.jsp?thread=126923  http://www.slideshare.net/nickokiss/unit-testing-best-practices http://www.nickokiss.com/2009/09/unit-testing.html