SlideShare a Scribd company logo
1 of 47
Download to read offline
Unit Testing
Foyzul Karim
foyzulkarim@gmail.com
Secure Link Services Limited
Unit testing? No need
1. Lets write a Math Calculator class.
It can
Add
Subtract
We know it will work because we have 'enough' confidence on it.
Unit testing? No need
2. Lets write a Regular Expression generator class.
It can
Generate Only Alpha Allowed expression with different length
Generate Only Alpha & Numeric Allowed expression with different length
Do you know your code will work before you test by yourself?
If you want to know whether your code is working or not, how would you test?
Create an User Interface Project? then
Put some input fields? then
Put an event trigger control (like button etc)? then
Call your regex method from this project UI?
You would do that.. won't you?
Any other idea?
How about...
If I say you to put your code under a testing machine. You don't need to test by
yourself using the UI, would you mind?
Lets see one of the most common testing tool of the world.
Anyone wouldn't dare to test that by his/her finger to calculate the result.
Or would anyone?
Why would you need that?
Because you don't need to manually input the values each of the time you want
to test
Because you don't need to input different values each of the time you want to
test
Because you don't need to click and press keyboards each of the time you
want to test
Because after you modify some of your classes you don't want to test manually
the rest other classes
And many more because left...
Who says to write unit test?
"Any program feature without an automated test simply doesn't exist"
Industrial Logic
I Don't know those guys
I have enough skill to write codes which act what I expect that to do..
I don't want to write Test Code because I am a
"Super Geek Alien Type Genius Programmer, Not a Tester"
Probably you know these
JQuery
Json.NET
Entity Framework
JQuery Validation
Microsoft.Web.Infrastructure
JQuery UI
Modernizer
Microsoft ASP.NET Razor 2
ELMAH
Ninject
So...
You will be unusual if you don’t write test code for your production code.
Lets test
Required:
Visual Studio 2012
Resharper 7.0
NUnit library
Moq library
Sql Server (any)
Lets test our Add method
public class MathCalculator
{
public int Add(int first, int second)
{
return first + second;
}
}
[TestFixture]
public class MathCalculatorFixture
{
[Test]
public void TestAddReturnsSum()
{
MathCalculator calculator=new MathCalculator();
int result = calculator.Add(10, 20);
Assert.AreEqual(30, result);
}
Debug vs Run
Displaying Error message
Criteria of GOOD Unit
Tests
Each of your test should focus on a single behaviour of a single method.
So it should be
Small
Precise
Independent
Fast
Flexible
Manual testing is superb !!!
What would you do if you don't have any unit testing framework to test the
Add() method we wrote just now?
Automated VS Manual Testing
[Industrial Logic]
Manual Tests is more expensive and time consuming
Manual Testing becomes mundane and boring
Automated Tests are reusable
Manual Tests provide limited Visibility and have to be repeated by all
Stakeholders
Automated Tests can have varying scopes and may require less complex setup
and teardown
Automated Testing ensures repeatability (missing out)
Automated Testing drives cleaner design
Automated Tests provide a Safety Net for Refactoring
Automated Tests are living up-to-date specification document
Automated Tests dose not clutter your code/console/logs
What the Guru's are
saying:
“Any program feature without an automated test simply doesn’t exist.”
from Extreme Programming Explained, Kent Beck
Practice time
We want to check that whether the username of the student object has
minimum 6 characters in length.
Lets test it.
Hints:
public class StudentManager
{
public bool IsAllowedToProceed(string userName)
{
…
...
}
}
Steps we should follow
Arrange
Prepare the objects and appropriate data
Act
Call the appropriate method
Assert
Assert the expected values with the actual values
What should we focus?
One test method should focus on a single behaviour of the method to be
tested.
If a single method can behave multiple ways, we should write different test
methods to test each of the expected scenarios.
More Practice...
Discussion and change of the requirements according to the audience level.
For example:
1. Create different criteria for a username to have and test those criteria
Lets discuss a project
Shortest path finder
Another Example scenario
A user can attempt to login 3 times sequentially. On failing the 3rd time, his
account will be locked. On the 4th time, his account can't be accessed
whether he gives valid credentials or not. After an hour he will be again able
to try to login.
Brainstorming time
Find out the possible criteria to test the scenario.
Lets discuss
Possible scenarios to test
So, the possible scenarios might be
1. Ideal case, where user inputs are valid and he will be given pass to proceed
2. Worst case, using invalid password, the user will try login 3 times in a
sequence and in the 4th time he will receive a account lock notification
3. User can not proceed to the next step if he inputs 3 times in a row, but in the
4th time he use the valid password because the system is locked
4. After one hour user can access the system and the counter is 1
5. After one hour blocking time user can login into the system with valid
password on the 4th time
Test Method is explaining
1. TestSigninIdealCase
2. TestSigninBlockCase
3. TestSigninBlockCaseResetWithValidPassword
4. TestSigninBlockCaseResetWithDelayedTime
5. TestSigninBlockCaseResetWithDelayedTimeWithValidPassword
and if required we would add more..
Now Lets discuss about the
Smells
http://www.revealingassets.ca/Home%20Staging%20Addresses%20Bad%20Smells.jpg
Unbearable Test Code
Smell
Don’t copy and paste
Don’t Repeat your code
Know your fixture
Don’t be optimistic
Do Assert
Be clear about the Unit Test Coverage
Know your Testing Framework
Don’t test everything at a time (image in next page)
Avoid inappropriate dependencies of your test method
Try: One Assertion per test
At least One concept per test
Appropriate error message
Designing Effective Micro
Tests
Do the Black-box testing with your class. Avoid white-box testing.
assertSame(element, list.get(0));
vs
assertSame(element, list.contents[0]);
A good unit test
Express intent, not implementation details
Small and Simple: Easy to quickly comprehend
Run fast (they have short setups, run times, and break downs)
Run in isolation (reordering possible)
Run in parallel
Use data that makes them easy to read and to understand
Frequently Run with every code change
Test is not unit test if
Has External Dependencies
It talks to the Database
It communicates across the Network
It touches the File System
You have to do special things to your Environment – (such as editing config
files) to run it
It can't run at the same time as any of your other unit tests
Order Dependencies - Only works when run in certain order
Do we need to follow all of
those to write unit test?
http://mattdturner.com/wordpress/wp-content/uploads/2012/07/Computer-frustration.jpg
Sometimes we tweak !!!
At least we can tweak according to our need instead of not writing them at all
So what we are tweaking
while testing Database
[Test]
public void TestGetShouldReturnUser()
{
using (TransactionScope scope=new TransactionScope())
{
IUserRepository repository = new UserRepository(new
GoldfishDbEntities());
User user = CreateUser();
repository.Save(user);
User returnedUser = repository.Get(user.Id);
Assert.AreEqual(user.Id,returnedUser.Id);
Assert.AreEqual(user.Gender,returnedUser.Gender);
}
}
Unit testing Advanced
Lets talk about the other attributes
Setup
Teardown
Inheritance in Unit Testing
Exception Expectations
How to write the test when our production code throws exceptions?
Practice (Sales tax)
Sales Tax Introduction
Basic sales tax is applicable at a rate of 10% on all goods, except books, food,
and medical products that are exempt.
Import duty is an additional sales tax applicable on all imported goods at a rate
of 5%, with no exemptions.
When I purchase items I receive a receipt, whichlists the name of all the items
and their price (including tax), finishing
with the total cost of the items, and the total amounts of sales taxes paid. The
rounding rules for sales tax are that for
a tax rate of n%, a shelf price of p contains (np/100 rounded up to the nearest
0.05) amount of sales tax.
Write an application that prints out the receipt details for these shopping
baskets.
Practice (Sales tax)
INPUT/OUTPUT:
Input 1:
1 book at 12.49
1 music CD at 14.99
1 chocolate bar at 0.85
Output 1:
1 book : 12.49
1 music CD: 16.49
1 chocolate bar: 0.85
Sales Taxes: 1.50
Total: 29.83
Input 2:
1 imported box of chocolates at 10.00
1 imported bottle of perfume at 47.50
Output 2:
1 imported box of chocolates: 10.50
1 imported bottle of perfume: 54.65
Sales Taxes: 7.65
Practice (Sales tax)
Input 3:
1 imported bottle of perfume at 27.99
1 bottle of perfume at 18.99
1 packet of headache pills at 9.75
1 box of imported chocolates at 11.25
Output 3:
1 imported bottle of perfume: 32.19
1 bottle of perfume: 20.89
1 packet of headache pills: 9.75
1 imported box of chocolates: 11.85
Sales Taxes: 6.70
Total: 74.68
Unit testing (workshop)

More Related Content

What's hot

Unit Testing Concepts and Best Practices
Unit Testing Concepts and Best PracticesUnit Testing Concepts and Best Practices
Unit Testing Concepts and Best PracticesDerek Smith
 
Clean Unit Test Patterns
Clean Unit Test PatternsClean Unit Test Patterns
Clean Unit Test PatternsFrank Appel
 
Unit tests & TDD
Unit tests & TDDUnit tests & TDD
Unit tests & TDDDror Helper
 
Unit testing
Unit testing Unit testing
Unit testing dubbu
 
Mock driven development using .NET
Mock driven development using .NETMock driven development using .NET
Mock driven development using .NETPuneet Ghanshani
 
Unit Testing Fundamentals
Unit Testing FundamentalsUnit Testing Fundamentals
Unit Testing FundamentalsRichard Paul
 
Unit Tests And Automated Testing
Unit Tests And Automated TestingUnit Tests And Automated Testing
Unit Tests And Automated TestingLee Englestone
 
Unit testing - the hard parts
Unit testing - the hard partsUnit testing - the hard parts
Unit testing - the hard partsShaun Abram
 
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
 
Getting Unstuck: Working with Legacy Code and Data
Getting Unstuck: Working with Legacy Code and DataGetting Unstuck: Working with Legacy Code and Data
Getting Unstuck: Working with Legacy Code and DataCory Foy
 

What's hot (19)

Unit Testing Concepts and Best Practices
Unit Testing Concepts and Best PracticesUnit Testing Concepts and Best Practices
Unit Testing Concepts and Best Practices
 
Clean Unit Test Patterns
Clean Unit Test PatternsClean Unit Test Patterns
Clean Unit Test Patterns
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
Unit Testing Your Application
Unit Testing Your ApplicationUnit Testing Your Application
Unit Testing Your Application
 
Unit test
Unit testUnit test
Unit test
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
Unit tests & TDD
Unit tests & TDDUnit tests & TDD
Unit tests & TDD
 
Unit testing
Unit testing Unit testing
Unit testing
 
Mock driven development using .NET
Mock driven development using .NETMock driven development using .NET
Mock driven development using .NET
 
Unit Testing Fundamentals
Unit Testing FundamentalsUnit Testing Fundamentals
Unit Testing Fundamentals
 
Unit Tests And Automated Testing
Unit Tests And Automated TestingUnit Tests And Automated Testing
Unit Tests And Automated Testing
 
Unit testing - the hard parts
Unit testing - the hard partsUnit testing - the hard parts
Unit testing - the hard parts
 
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 101
Unit Testing 101Unit Testing 101
Unit Testing 101
 
Getting Unstuck: Working with Legacy Code and Data
Getting Unstuck: Working with Legacy Code and DataGetting Unstuck: Working with Legacy Code and Data
Getting Unstuck: Working with Legacy Code and Data
 
Workshop unit test
Workshop   unit testWorkshop   unit test
Workshop unit test
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
Unit Testing (C#)
Unit Testing (C#)Unit Testing (C#)
Unit Testing (C#)
 
Why Unit Testingl
Why Unit TestinglWhy Unit Testingl
Why Unit Testingl
 

Viewers also liked

Windows store app development using javascript
Windows store app development using javascriptWindows store app development using javascript
Windows store app development using javascriptFoyzul Karim
 
An Introduction to Unit Test Using NUnit
An Introduction to Unit Test Using NUnitAn Introduction to Unit Test Using NUnit
An Introduction to Unit Test Using NUnitweili_at_slideshare
 
Unit testing with NUnit
Unit testing with NUnitUnit testing with NUnit
Unit testing with NUnitkleinron
 
Introduction to testing with MSTest, Visual Studio, and Team Foundation Serve...
Introduction to testing with MSTest, Visual Studio, and Team Foundation Serve...Introduction to testing with MSTest, Visual Studio, and Team Foundation Serve...
Introduction to testing with MSTest, Visual Studio, and Team Foundation Serve...Thomas Weller
 

Viewers also liked (7)

Windows store app development using javascript
Windows store app development using javascriptWindows store app development using javascript
Windows store app development using javascript
 
Nunit
NunitNunit
Nunit
 
An Introduction to Unit Test Using NUnit
An Introduction to Unit Test Using NUnitAn Introduction to Unit Test Using NUnit
An Introduction to Unit Test Using NUnit
 
Unit testing with NUnit
Unit testing with NUnitUnit testing with NUnit
Unit testing with NUnit
 
Nunit
NunitNunit
Nunit
 
Introduction to testing with MSTest, Visual Studio, and Team Foundation Serve...
Introduction to testing with MSTest, Visual Studio, and Team Foundation Serve...Introduction to testing with MSTest, Visual Studio, and Team Foundation Serve...
Introduction to testing with MSTest, Visual Studio, and Team Foundation Serve...
 
NUnit vs MSTest
NUnit vs MSTestNUnit vs MSTest
NUnit vs MSTest
 

Similar to Unit testing (workshop)

assertYourself - Breaking the Theories and Assumptions of Unit Testing in Flex
assertYourself - Breaking the Theories and Assumptions of Unit Testing in FlexassertYourself - Breaking the Theories and Assumptions of Unit Testing in Flex
assertYourself - Breaking the Theories and Assumptions of Unit Testing in Flexmichael.labriola
 
[Rakuten TechConf2014] [G-4] Beyond Agile Testing to Lean Development
[Rakuten TechConf2014] [G-4] Beyond Agile Testing to Lean Development[Rakuten TechConf2014] [G-4] Beyond Agile Testing to Lean Development
[Rakuten TechConf2014] [G-4] Beyond Agile Testing to Lean DevelopmentRakuten Group, Inc.
 
Practical unit testing tips
Practical unit testing tipsPractical unit testing tips
Practical unit testing tipsTypemock
 
SE2_Lec 21_ TDD and Junit
SE2_Lec 21_ TDD and JunitSE2_Lec 21_ TDD and Junit
SE2_Lec 21_ TDD and JunitAmr E. Mohamed
 
Test driven development
Test driven developmentTest driven development
Test driven developmentnamkha87
 
DotNet unit testing training
DotNet unit testing trainingDotNet unit testing training
DotNet unit testing trainingTom Tang
 
The Testing Planet Issue 2
The Testing Planet Issue 2The Testing Planet Issue 2
The Testing Planet Issue 2Rosie Sherry
 
10 Principles of Apex Testing
10 Principles of Apex Testing10 Principles of Apex Testing
10 Principles of Apex TestingKevin Poorman
 
J unit a starter guide
J unit a starter guideJ unit a starter guide
J unit a starter guideselfishson83
 
Expressive Testing ...and your Code For Free?
Expressive Testing ...and your Code For Free?Expressive Testing ...and your Code For Free?
Expressive Testing ...and your Code For Free?ESUG
 
SE2018_Lec 20_ Test-Driven Development (TDD)
SE2018_Lec 20_ Test-Driven Development (TDD)SE2018_Lec 20_ Test-Driven Development (TDD)
SE2018_Lec 20_ Test-Driven Development (TDD)Amr E. Mohamed
 
Testers Desk Presentation
Testers Desk PresentationTesters Desk Presentation
Testers Desk PresentationQuality Testing
 

Similar to Unit testing (workshop) (20)

TDD Best Practices
TDD Best PracticesTDD Best Practices
TDD Best Practices
 
Why Unit Testingl
Why Unit TestinglWhy Unit Testingl
Why Unit Testingl
 
Why unit testingl
Why unit testinglWhy unit testingl
Why unit testingl
 
assertYourself - Breaking the Theories and Assumptions of Unit Testing in Flex
assertYourself - Breaking the Theories and Assumptions of Unit Testing in FlexassertYourself - Breaking the Theories and Assumptions of Unit Testing in Flex
assertYourself - Breaking the Theories and Assumptions of Unit Testing in Flex
 
[Rakuten TechConf2014] [G-4] Beyond Agile Testing to Lean Development
[Rakuten TechConf2014] [G-4] Beyond Agile Testing to Lean Development[Rakuten TechConf2014] [G-4] Beyond Agile Testing to Lean Development
[Rakuten TechConf2014] [G-4] Beyond Agile Testing to Lean Development
 
Practical unit testing tips
Practical unit testing tipsPractical unit testing tips
Practical unit testing tips
 
SE2_Lec 21_ TDD and Junit
SE2_Lec 21_ TDD and JunitSE2_Lec 21_ TDD and Junit
SE2_Lec 21_ TDD and Junit
 
Unit testing - A&BP CC
Unit testing - A&BP CCUnit testing - A&BP CC
Unit testing - A&BP CC
 
Test driven development
Test driven developmentTest driven development
Test driven development
 
DotNet unit testing training
DotNet unit testing trainingDotNet unit testing training
DotNet unit testing training
 
Unit testing - An introduction
Unit testing - An introductionUnit testing - An introduction
Unit testing - An introduction
 
The Testing Planet Issue 2
The Testing Planet Issue 2The Testing Planet Issue 2
The Testing Planet Issue 2
 
Test Driven
Test DrivenTest Driven
Test Driven
 
Unit testing
Unit testingUnit testing
Unit testing
 
10 Principles of Apex Testing
10 Principles of Apex Testing10 Principles of Apex Testing
10 Principles of Apex Testing
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
J unit a starter guide
J unit a starter guideJ unit a starter guide
J unit a starter guide
 
Expressive Testing ...and your Code For Free?
Expressive Testing ...and your Code For Free?Expressive Testing ...and your Code For Free?
Expressive Testing ...and your Code For Free?
 
SE2018_Lec 20_ Test-Driven Development (TDD)
SE2018_Lec 20_ Test-Driven Development (TDD)SE2018_Lec 20_ Test-Driven Development (TDD)
SE2018_Lec 20_ Test-Driven Development (TDD)
 
Testers Desk Presentation
Testers Desk PresentationTesters Desk Presentation
Testers Desk Presentation
 

More from Foyzul Karim

Software architecture : From project management to deployment
Software architecture : From project management to deploymentSoftware architecture : From project management to deployment
Software architecture : From project management to deploymentFoyzul Karim
 
SDLC, Agile methodologies and Career in Product management
SDLC, Agile methodologies and Career in Product managementSDLC, Agile methodologies and Career in Product management
SDLC, Agile methodologies and Career in Product managementFoyzul Karim
 
Software architecture
Software architectureSoftware architecture
Software architectureFoyzul Karim
 
A practical approach on - How to design offline-online synchronization system
A practical approach on - How to design offline-online synchronization systemA practical approach on - How to design offline-online synchronization system
A practical approach on - How to design offline-online synchronization systemFoyzul Karim
 
BizBook365 : A microservice approach
BizBook365 : A microservice approachBizBook365 : A microservice approach
BizBook365 : A microservice approachFoyzul Karim
 
Microservices: A developer's approach
Microservices: A developer's approachMicroservices: A developer's approach
Microservices: A developer's approachFoyzul Karim
 
Software design principles SOLID
Software design principles SOLIDSoftware design principles SOLID
Software design principles SOLIDFoyzul Karim
 
BizBook365.com 16Feb2018 Demo
BizBook365.com 16Feb2018 DemoBizBook365.com 16Feb2018 Demo
BizBook365.com 16Feb2018 DemoFoyzul Karim
 
Angular4 kickstart
Angular4 kickstartAngular4 kickstart
Angular4 kickstartFoyzul Karim
 
BizBook365 - Modern Inventory System for Shops
BizBook365 - Modern Inventory System for ShopsBizBook365 - Modern Inventory System for Shops
BizBook365 - Modern Inventory System for ShopsFoyzul Karim
 
Kickstart android development with xamarin
Kickstart android development with xamarinKickstart android development with xamarin
Kickstart android development with xamarinFoyzul Karim
 
Windows store app development V1
Windows store app development V1Windows store app development V1
Windows store app development V1Foyzul Karim
 

More from Foyzul Karim (14)

Software architecture : From project management to deployment
Software architecture : From project management to deploymentSoftware architecture : From project management to deployment
Software architecture : From project management to deployment
 
SDLC, Agile methodologies and Career in Product management
SDLC, Agile methodologies and Career in Product managementSDLC, Agile methodologies and Career in Product management
SDLC, Agile methodologies and Career in Product management
 
Software architecture
Software architectureSoftware architecture
Software architecture
 
A practical approach on - How to design offline-online synchronization system
A practical approach on - How to design offline-online synchronization systemA practical approach on - How to design offline-online synchronization system
A practical approach on - How to design offline-online synchronization system
 
BizBook365 : A microservice approach
BizBook365 : A microservice approachBizBook365 : A microservice approach
BizBook365 : A microservice approach
 
Microservices: A developer's approach
Microservices: A developer's approachMicroservices: A developer's approach
Microservices: A developer's approach
 
Software design principles SOLID
Software design principles SOLIDSoftware design principles SOLID
Software design principles SOLID
 
BizBook365.com 16Feb2018 Demo
BizBook365.com 16Feb2018 DemoBizBook365.com 16Feb2018 Demo
BizBook365.com 16Feb2018 Demo
 
Angular4 kickstart
Angular4 kickstartAngular4 kickstart
Angular4 kickstart
 
BizBook365 - Modern Inventory System for Shops
BizBook365 - Modern Inventory System for ShopsBizBook365 - Modern Inventory System for Shops
BizBook365 - Modern Inventory System for Shops
 
Kickstart android development with xamarin
Kickstart android development with xamarinKickstart android development with xamarin
Kickstart android development with xamarin
 
Windows store app development V1
Windows store app development V1Windows store app development V1
Windows store app development V1
 
Data types
Data typesData types
Data types
 
Linq
LinqLinq
Linq
 

Recently uploaded

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
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
[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.pdfhans926745
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
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
 
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
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
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 WorkerThousandEyes
 
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 organizationRadu Cotescu
 
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
 

Recently uploaded (20)

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
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
[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
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
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
 
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
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
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
 
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
 
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
 

Unit testing (workshop)

  • 2. Unit testing? No need 1. Lets write a Math Calculator class. It can Add Subtract We know it will work because we have 'enough' confidence on it.
  • 3. Unit testing? No need 2. Lets write a Regular Expression generator class. It can Generate Only Alpha Allowed expression with different length Generate Only Alpha & Numeric Allowed expression with different length Do you know your code will work before you test by yourself? If you want to know whether your code is working or not, how would you test? Create an User Interface Project? then Put some input fields? then Put an event trigger control (like button etc)? then Call your regex method from this project UI? You would do that.. won't you? Any other idea?
  • 4. How about... If I say you to put your code under a testing machine. You don't need to test by yourself using the UI, would you mind? Lets see one of the most common testing tool of the world. Anyone wouldn't dare to test that by his/her finger to calculate the result. Or would anyone?
  • 5.
  • 6.
  • 7. Why would you need that? Because you don't need to manually input the values each of the time you want to test Because you don't need to input different values each of the time you want to test Because you don't need to click and press keyboards each of the time you want to test Because after you modify some of your classes you don't want to test manually the rest other classes And many more because left...
  • 8. Who says to write unit test? "Any program feature without an automated test simply doesn't exist" Industrial Logic
  • 9. I Don't know those guys I have enough skill to write codes which act what I expect that to do.. I don't want to write Test Code because I am a "Super Geek Alien Type Genius Programmer, Not a Tester"
  • 10. Probably you know these JQuery Json.NET Entity Framework JQuery Validation Microsoft.Web.Infrastructure JQuery UI Modernizer Microsoft ASP.NET Razor 2 ELMAH Ninject
  • 11.
  • 12.
  • 13.
  • 14. So... You will be unusual if you don’t write test code for your production code.
  • 15. Lets test Required: Visual Studio 2012 Resharper 7.0 NUnit library Moq library Sql Server (any)
  • 16. Lets test our Add method public class MathCalculator { public int Add(int first, int second) { return first + second; } } [TestFixture] public class MathCalculatorFixture { [Test] public void TestAddReturnsSum() { MathCalculator calculator=new MathCalculator(); int result = calculator.Add(10, 20); Assert.AreEqual(30, result); }
  • 19. Criteria of GOOD Unit Tests Each of your test should focus on a single behaviour of a single method. So it should be Small Precise Independent Fast Flexible
  • 20. Manual testing is superb !!! What would you do if you don't have any unit testing framework to test the Add() method we wrote just now?
  • 21. Automated VS Manual Testing [Industrial Logic] Manual Tests is more expensive and time consuming Manual Testing becomes mundane and boring Automated Tests are reusable Manual Tests provide limited Visibility and have to be repeated by all Stakeholders Automated Tests can have varying scopes and may require less complex setup and teardown Automated Testing ensures repeatability (missing out) Automated Testing drives cleaner design Automated Tests provide a Safety Net for Refactoring Automated Tests are living up-to-date specification document Automated Tests dose not clutter your code/console/logs
  • 22. What the Guru's are saying: “Any program feature without an automated test simply doesn’t exist.” from Extreme Programming Explained, Kent Beck
  • 23. Practice time We want to check that whether the username of the student object has minimum 6 characters in length. Lets test it. Hints: public class StudentManager { public bool IsAllowedToProceed(string userName) { … ... } }
  • 24. Steps we should follow Arrange Prepare the objects and appropriate data Act Call the appropriate method Assert Assert the expected values with the actual values
  • 25. What should we focus? One test method should focus on a single behaviour of the method to be tested. If a single method can behave multiple ways, we should write different test methods to test each of the expected scenarios.
  • 26. More Practice... Discussion and change of the requirements according to the audience level. For example: 1. Create different criteria for a username to have and test those criteria
  • 27. Lets discuss a project Shortest path finder
  • 28. Another Example scenario A user can attempt to login 3 times sequentially. On failing the 3rd time, his account will be locked. On the 4th time, his account can't be accessed whether he gives valid credentials or not. After an hour he will be again able to try to login.
  • 29. Brainstorming time Find out the possible criteria to test the scenario. Lets discuss
  • 30. Possible scenarios to test So, the possible scenarios might be 1. Ideal case, where user inputs are valid and he will be given pass to proceed 2. Worst case, using invalid password, the user will try login 3 times in a sequence and in the 4th time he will receive a account lock notification 3. User can not proceed to the next step if he inputs 3 times in a row, but in the 4th time he use the valid password because the system is locked 4. After one hour user can access the system and the counter is 1 5. After one hour blocking time user can login into the system with valid password on the 4th time
  • 31. Test Method is explaining 1. TestSigninIdealCase 2. TestSigninBlockCase 3. TestSigninBlockCaseResetWithValidPassword 4. TestSigninBlockCaseResetWithDelayedTime 5. TestSigninBlockCaseResetWithDelayedTimeWithValidPassword and if required we would add more..
  • 32. Now Lets discuss about the Smells http://www.revealingassets.ca/Home%20Staging%20Addresses%20Bad%20Smells.jpg
  • 33. Unbearable Test Code Smell Don’t copy and paste Don’t Repeat your code Know your fixture Don’t be optimistic Do Assert Be clear about the Unit Test Coverage Know your Testing Framework Don’t test everything at a time (image in next page) Avoid inappropriate dependencies of your test method Try: One Assertion per test At least One concept per test Appropriate error message
  • 34.
  • 35. Designing Effective Micro Tests Do the Black-box testing with your class. Avoid white-box testing. assertSame(element, list.get(0)); vs assertSame(element, list.contents[0]);
  • 36. A good unit test Express intent, not implementation details Small and Simple: Easy to quickly comprehend Run fast (they have short setups, run times, and break downs) Run in isolation (reordering possible) Run in parallel Use data that makes them easy to read and to understand Frequently Run with every code change
  • 37. Test is not unit test if Has External Dependencies It talks to the Database It communicates across the Network It touches the File System You have to do special things to your Environment – (such as editing config files) to run it It can't run at the same time as any of your other unit tests Order Dependencies - Only works when run in certain order
  • 38. Do we need to follow all of those to write unit test? http://mattdturner.com/wordpress/wp-content/uploads/2012/07/Computer-frustration.jpg
  • 39. Sometimes we tweak !!! At least we can tweak according to our need instead of not writing them at all
  • 40. So what we are tweaking while testing Database [Test] public void TestGetShouldReturnUser() { using (TransactionScope scope=new TransactionScope()) { IUserRepository repository = new UserRepository(new GoldfishDbEntities()); User user = CreateUser(); repository.Save(user); User returnedUser = repository.Get(user.Id); Assert.AreEqual(user.Id,returnedUser.Id); Assert.AreEqual(user.Gender,returnedUser.Gender); } }
  • 41. Unit testing Advanced Lets talk about the other attributes Setup Teardown
  • 43. Exception Expectations How to write the test when our production code throws exceptions?
  • 44. Practice (Sales tax) Sales Tax Introduction Basic sales tax is applicable at a rate of 10% on all goods, except books, food, and medical products that are exempt. Import duty is an additional sales tax applicable on all imported goods at a rate of 5%, with no exemptions. When I purchase items I receive a receipt, whichlists the name of all the items and their price (including tax), finishing with the total cost of the items, and the total amounts of sales taxes paid. The rounding rules for sales tax are that for a tax rate of n%, a shelf price of p contains (np/100 rounded up to the nearest 0.05) amount of sales tax. Write an application that prints out the receipt details for these shopping baskets.
  • 45. Practice (Sales tax) INPUT/OUTPUT: Input 1: 1 book at 12.49 1 music CD at 14.99 1 chocolate bar at 0.85 Output 1: 1 book : 12.49 1 music CD: 16.49 1 chocolate bar: 0.85 Sales Taxes: 1.50 Total: 29.83 Input 2: 1 imported box of chocolates at 10.00 1 imported bottle of perfume at 47.50 Output 2: 1 imported box of chocolates: 10.50 1 imported bottle of perfume: 54.65 Sales Taxes: 7.65
  • 46. Practice (Sales tax) Input 3: 1 imported bottle of perfume at 27.99 1 bottle of perfume at 18.99 1 packet of headache pills at 9.75 1 box of imported chocolates at 11.25 Output 3: 1 imported bottle of perfume: 32.19 1 bottle of perfume: 20.89 1 packet of headache pills: 9.75 1 imported box of chocolates: 11.85 Sales Taxes: 6.70 Total: 74.68