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 is JUnit? | Edureka
What is JUnit? | EdurekaWhat is JUnit? | Edureka
What is JUnit? | EdurekaEdureka!
 
Test Automation
Test AutomationTest Automation
Test Automationrockoder
 
Agile Testing: The Role Of The Agile Tester
Agile Testing: The Role Of The Agile TesterAgile Testing: The Role Of The Agile Tester
Agile Testing: The Role Of The Agile TesterDeclan Whelan
 
Introduction to performance testing
Introduction to performance testingIntroduction to performance testing
Introduction to performance testingTharinda Liyanage
 
Test Cases Maintaining & Documenting
Test Cases Maintaining & DocumentingTest Cases Maintaining & Documenting
Test Cases Maintaining & DocumentingSeyed Ali Marjaie
 
C++ Unit Test with Google Testing Framework
C++ Unit Test with Google Testing FrameworkC++ Unit Test with Google Testing Framework
C++ Unit Test with Google Testing FrameworkHumberto Marchezi
 
Unit testing with NUnit
Unit testing with NUnitUnit testing with NUnit
Unit testing with NUnitkleinron
 
Difference between functional testing and non functional testing
Difference between functional testing and non functional testingDifference between functional testing and non functional testing
Difference between functional testing and non functional testingpooja deshmukh
 
Robot Framework Introduction
Robot Framework IntroductionRobot Framework Introduction
Robot Framework IntroductionPekka Klärck
 
TestNG introduction
TestNG introductionTestNG introduction
TestNG introductionDenis Bazhin
 
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 .NETBaskar K
 

What's hot (20)

Unit Testing
Unit TestingUnit Testing
Unit Testing
 
What is JUnit? | Edureka
What is JUnit? | EdurekaWhat is JUnit? | Edureka
What is JUnit? | Edureka
 
Test Automation
Test AutomationTest Automation
Test Automation
 
Test Automation
Test AutomationTest Automation
Test Automation
 
Automation testing
Automation testingAutomation testing
Automation testing
 
Agile Testing: The Role Of The Agile Tester
Agile Testing: The Role Of The Agile TesterAgile Testing: The Role Of The Agile Tester
Agile Testing: The Role Of The Agile Tester
 
Introduction to performance testing
Introduction to performance testingIntroduction to performance testing
Introduction to performance testing
 
Testing fundamentals
Testing fundamentalsTesting fundamentals
Testing fundamentals
 
Test cases
Test casesTest cases
Test cases
 
Test Cases Maintaining & Documenting
Test Cases Maintaining & DocumentingTest Cases Maintaining & Documenting
Test Cases Maintaining & Documenting
 
C++ Unit Test with Google Testing Framework
C++ Unit Test with Google Testing FrameworkC++ Unit Test with Google Testing Framework
C++ Unit Test with Google Testing Framework
 
Unit testing with NUnit
Unit testing with NUnitUnit testing with NUnit
Unit testing with NUnit
 
Workshop unit test
Workshop   unit testWorkshop   unit test
Workshop unit test
 
TestNG Framework
TestNG Framework TestNG Framework
TestNG Framework
 
Difference between functional testing and non functional testing
Difference between functional testing and non functional testingDifference between functional testing and non functional testing
Difference between functional testing and non functional testing
 
Robot Framework Introduction
Robot Framework IntroductionRobot Framework Introduction
Robot Framework Introduction
 
TestNG introduction
TestNG introductionTestNG introduction
TestNG introduction
 
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
 
TDD and BDD and ATDD
TDD and BDD and ATDDTDD and BDD and ATDD
TDD and BDD and ATDD
 
Sanity testing and smoke testing
Sanity testing and smoke testingSanity testing and smoke testing
Sanity testing and smoke 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
 

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
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
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
 

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

Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 

Recently uploaded (20)

Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 

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