SlideShare a Scribd company logo
.NET Unit Test Session
Prepared By:
Tom Tang
tomang0406@gmail.com
Dec. 2010 (v1.0)
●Concept
●Implementation
●Challenge
●Automation – Hudson
●Professional guideline
●Q & A and sharing
CONCEPT
About unit test
Concept
●Why unit test?
oPrevent side-effect as less as possible.
oImprove code quality and stability.
oImprove maintainability.
oConsolidate design.
oSave time from manual testing in the future.
oDescribe the usage of your libraries and classes.
Concept
●How unit test help our code quality?
When you are doing implementation…
oHow do you confirm your design “loosely-coupled” well
enough?
oHow do you keep the correct behavior of the class you’re
updating?
oHow do you ensure you have fixed the bug?
oHow do you describe some tricky design / use case?
●Key rule: Cut off all dependency!!!
1.Human interaction dependency(UI)
2.Library dependency
3.Sequence dependency
4.Environment dependency
5.Hierarchy dependency
Concept
●Cost - You must pay, then gain…
oWrite code to verify code: More code, more bug.
oCost much more time than real functional implementation.
oMuch more code have to be maintained.
Exchange short-term effort for long-term benefit.
Concept
●Mind construction:
oDo not think coverage, JUST DO IT®.
oTest case shall keep growing, never think approach all at one
time.
oIt saves the future, not save the present.
oDoing unit test is never easy, so it make quality competitive.
There’s no silver bullet.
IMPLEMENTATION
What to do? How to do?
Implementation
Introduce Visual Studio built-in unit test tool:
Implementation
Best practice policy:
1.Every public entry must have at least 1 unit test case.
2.Pair programming technique –
One implement test case, the other one implement functionality.
3.TDD (Not DDT) –
Test-Driven Development –
Implement test case before implement functional code.
Implementation
TDD life-cycle:
Define interface
(empty class)
Write test code
through the
interface
Test Failure.
Implement
functional class.
Pass test case
Commit
Developer A
Developer B
Implementation
Unit test running life-cycle for a class:
ClassInitialize
TestInitialize
TestMethod
TestCleanup
ClassCleanup
TestInitialize
TestMethod
TestCleanup
Implementation
How to do a useful test case:
●Awful, but at least it prevents run-time exception in some case.
●Better one:
Implementation
How to do a useful test case:
●Is this one good idea?
Better to avoid this style, keep the meaning of “unit” in mind.
Implementation
How to do a useful test case:
The other bad sample…
Some genius developer write a perfect bug-free implementation, how come it failed to pass test
case:
??
Implementation
How to do a useful test case:
The other bad sample…
Updating test case assume there’s an existing member…
After running the creating test case, the updating test case passed.
There’s a test case sequential dependency.
Once a test case can’t be executed alone,
it’s NOT an unit test case.
Implementation
How to do a useful test case:
How to make the case better…
Preparing its own precondition is every unit test case’s “Ownership”!
Implementation
How to do a useful test case:
How to test error handling…
FunSpec: Once user try to create duplicated member, we shall throw exception to alert user.
Implementation
How to do a useful test case:
How to follow up?
1.Don’t do new unit-test case by only coverage reason.
2.Build new test case by JIRA Ticket.
Implementation
Ticket unit test life-cycle:
Got ticket
Write test code
to reproduce
the case
Test Failure.
Fix the bug.
Pass test case
Commit
QA verify
Implementation
Ticket unit test life-cycle:
●Example – PMO-3357
Implementation
Ticket unit test life-cycle:
●Example – PMO-3357
Implementation
Promotion unit test demo:
Implementation
Promotion unit test demo:
CHALLENGE
Tricky technique to cut-off dependency
Challenge
How to cut-off dependency?
Use MVC design to separate logic and UI
private void OnButtonClick(EventArg e) {
if (txtBox1.Text == “ABC”) {
txtAnswer.Text = “XXX”;
} else if (txtBox1.Text == “DEF”) {
txtAnswer.Text = “YYY”;
}
}
Change code design like this:
private void OnButtonClick(EventArg e) {
txtAnswer.Text = new Controller().GetAnswer(txtText1.Text);
}
// controller class can be unit tested.
public class Controller {
public string GetAnswer(string input) {
if (input == “ABC”) {
return “XXX”;
} else if (input == “DEF”) {
return “YYY”;
}
}
}
Challenge
How to cut-off dependency?
Library dependency:
You want to test “ClassA”, but “ClassA” associated with “ClassB”, and
you don’t want to involve “ClassB” in this test case.
public class MathTool
{
public int AddNumber(int a, int b)
{
BackendService service = new BackendService(); // Dependency happen here.
return service.AddNumberWebservice(a, b);
}
}
public class BackendService {
public int AddNumberWebservice(int a, int b) {
HttpClient client = new HttpClient();
client.Url = "http://LiveMathTeacher.spi/AddNumber.asmx";
client.SubmitData(a, b);
int c = (int)client.GetResponseData();
return c;
}
}
Challenge
public class BackendService : IService {
public int AddNumberWebservice(int a, int b) {
HttpClient client = new HttpClient();
client.Url = "http://LiveMathTeacher.spi/AddNumber.asmx";
client.SubmitData(a, b);
int c = (int)client.GetResponseData();
return c;
}
}
public class MockService : IService {
public int AddNumberWebservice(int a, int b) {
return a + b;
}
}
Challenge
How to cut-off dependency?
Environment Dependency:
●If your class must access environment resource, like container(IIS)…
public string GetLoginUserName() {
if (CheckToken((string)Request[“token”])) // It accesses HTTP request resource
return (string)Session[“UserName”]; // It accesses IIS memory
}
Encapsulate those resource into tool classes:
public class SessionManager {
#if(UNIT_TEST)
// Use Dictionary structure to replace Session in unit-test
public static Dictionary<string, object> Session = new Dictionary<string, object>();
#else
public static HttpSessionState Session = HttpContext.Current.Session;
#endif
}
Use similar class for switching:
public string GetLoginUserName() {
if (CheckToken((string)RequestManager.Request[“token”]))
return (string)SessionManager.Session[“UserName”];
}
Challenge
How to cut-off dependency?
Hierarchy Dependency:
●If your class inherits from the other class which you don’t have source(3rd
party library…etc) and the base class would access any other dependency
that you can’t cut-off…
Examples:
// This class inherits from System.ServiceProcess.ServiceBase, its constructor will auto access environment resource.
using System.ServiceProcess;
public class MyService : ServiceBase { }
// This class inherits from System.Web.UI.Page, it’s ASP.NET class and access IIS resource.
using System.Web.UI;
public class MyPage : Page { }
Challenge
AUTOMATION - HUDSON
Unit test with automation
Automation - hudson
Integrate unit test with Hudson:
Visit this URL for sample:
http://xxx.xxx.xxx/view/banana%20DEV/job/backend.UnitTest/
Automation - hudson
Integrate unit test with Hudson:
Automation - hudson
Integrate unit test with Hudson:
PROFESSIONAL GUIDELINE
Sample review
Professional guideline
Extract the summary from the book “Pragmatic Unit Test”:
General Principles:
1.Test anything that might break
2.Test everything that does break
3.New code is guilty until proven innocent
4.Write at least as much test code as
production code
5.Run local tests with each compile
6.Run all tests before check-in to repository
Questions to Ask:
1.If the code ran correctly, how would I know?
2.How am I going to test this?
3.What else can go wrong?
4.Could this same kind of problem happen
anywhere else?
Professional guide line
Extract the summary from the book “Pragmatic Unit Test”:
What to Test: Use Your RIGHT-BICEP
1.Are the results right?
2.Are all the boundary conditions CORRECT?
3.Can you check inverse relationships?
4.Can you cross-check results using other
means?
5.Can you force error conditions to happen?
6.Are performance characteristics within
bounds?
Good tests are A TRIP
1.Automatic
2.Thorough
3.Repeatable
4.Independent
5.Professional
Professional guide line
Extract the summary from the book “Pragmatic Unit Test”:
CORRECT Boundary Conditions
1.Conformance - Does the value conform to an
expected format?
2.Ordering - Is the set of values ordered or
unordered as appropriate?
3.Range - Is the value within reasonable
minimum and maximum values?
4.Reference - Does the code reference
anything external that isn‘t under direct control
of the code itself?
5.Existence - Does the value exist? (e.g., is
non-null, non-zero, present in a set, etc.)
6.Cardinality - Are there exactly enough
values?
7.Time (absolute and relative) - Is everything
happening in order? At the right time? In
time?
Q & A AND SHARING
How to configure Strawberry
THANKS
The end

More Related Content

What's hot

TDD - Test Driven Development
TDD - Test Driven DevelopmentTDD - Test Driven Development
TDD - Test Driven Development
Tung Nguyen Thanh
 
Coldbox developer training – session 4
Coldbox developer training – session 4Coldbox developer training – session 4
Coldbox developer training – session 4Billie Berzinskas
 
Node.js exception handling
Node.js exception handlingNode.js exception handling
Node.js exception handling
Minh Hoang
 
VT.NET 20160411: An Intro to Test Driven Development (TDD)
VT.NET 20160411: An Intro to Test Driven Development (TDD)VT.NET 20160411: An Intro to Test Driven Development (TDD)
VT.NET 20160411: An Intro to Test Driven Development (TDD)
Rob Hale
 
@LinkingNote annotation in YATSPEC
@LinkingNote annotation in YATSPEC@LinkingNote annotation in YATSPEC
@LinkingNote annotation in YATSPEC
Wojciech Bulaty
 
Unit Testing in Action - C#, NUnit, and Moq
Unit Testing in Action - C#, NUnit, and MoqUnit Testing in Action - C#, NUnit, and Moq
Unit Testing in Action - C#, NUnit, and Moq
XPDays
 
Google test training
Google test trainingGoogle test training
Google test training
Thierry Gayet
 
Test-Driven Development
Test-Driven DevelopmentTest-Driven Development
Test-Driven Development
John Blum
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
Consulthinkspa
 
Dependency Injection in iOS
Dependency Injection in iOSDependency Injection in iOS
Dependency Injection in iOS
Pablo Villar
 
Test Driven Development (TDD) Preso 360|Flex 2010
Test Driven Development (TDD) Preso 360|Flex 2010Test Driven Development (TDD) Preso 360|Flex 2010
Test Driven Development (TDD) Preso 360|Flex 2010
guest5639fa9
 
Writing useful automated tests for the single page applications you build
Writing useful automated tests for the single page applications you buildWriting useful automated tests for the single page applications you build
Writing useful automated tests for the single page applications you build
Andrei Sebastian Cîmpean
 
TDD And Refactoring
TDD And RefactoringTDD And Refactoring
TDD And Refactoring
Naresh Jain
 
iOS Test-Driven Development
iOS Test-Driven DevelopmentiOS Test-Driven Development
iOS Test-Driven Development
Pablo Villar
 
Roy Osherove on Unit Testing Good Practices and Horrible Mistakes
Roy Osherove on Unit Testing Good Practices and Horrible MistakesRoy Osherove on Unit Testing Good Practices and Horrible Mistakes
Roy Osherove on Unit Testing Good Practices and Horrible MistakesRoy Osherove
 
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
michael.labriola
 
Working Effectively with Legacy Code
Working Effectively with Legacy CodeWorking Effectively with Legacy Code
Working Effectively with Legacy Code
Orbit One - We create coherence
 
Unit Testing Fundamentals
Unit Testing FundamentalsUnit Testing Fundamentals
Unit Testing FundamentalsRichard Paul
 
Test-Driven Development (TDD)
Test-Driven Development (TDD)Test-Driven Development (TDD)
Test-Driven Development (TDD)
Brian Rasmussen
 
Implementing Quality on a Java Project
Implementing Quality on a Java ProjectImplementing Quality on a Java Project
Implementing Quality on a Java Project
Vincent Massol
 

What's hot (20)

TDD - Test Driven Development
TDD - Test Driven DevelopmentTDD - Test Driven Development
TDD - Test Driven Development
 
Coldbox developer training – session 4
Coldbox developer training – session 4Coldbox developer training – session 4
Coldbox developer training – session 4
 
Node.js exception handling
Node.js exception handlingNode.js exception handling
Node.js exception handling
 
VT.NET 20160411: An Intro to Test Driven Development (TDD)
VT.NET 20160411: An Intro to Test Driven Development (TDD)VT.NET 20160411: An Intro to Test Driven Development (TDD)
VT.NET 20160411: An Intro to Test Driven Development (TDD)
 
@LinkingNote annotation in YATSPEC
@LinkingNote annotation in YATSPEC@LinkingNote annotation in YATSPEC
@LinkingNote annotation in YATSPEC
 
Unit Testing in Action - C#, NUnit, and Moq
Unit Testing in Action - C#, NUnit, and MoqUnit Testing in Action - C#, NUnit, and Moq
Unit Testing in Action - C#, NUnit, and Moq
 
Google test training
Google test trainingGoogle test training
Google test training
 
Test-Driven Development
Test-Driven DevelopmentTest-Driven Development
Test-Driven Development
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Dependency Injection in iOS
Dependency Injection in iOSDependency Injection in iOS
Dependency Injection in iOS
 
Test Driven Development (TDD) Preso 360|Flex 2010
Test Driven Development (TDD) Preso 360|Flex 2010Test Driven Development (TDD) Preso 360|Flex 2010
Test Driven Development (TDD) Preso 360|Flex 2010
 
Writing useful automated tests for the single page applications you build
Writing useful automated tests for the single page applications you buildWriting useful automated tests for the single page applications you build
Writing useful automated tests for the single page applications you build
 
TDD And Refactoring
TDD And RefactoringTDD And Refactoring
TDD And Refactoring
 
iOS Test-Driven Development
iOS Test-Driven DevelopmentiOS Test-Driven Development
iOS Test-Driven Development
 
Roy Osherove on Unit Testing Good Practices and Horrible Mistakes
Roy Osherove on Unit Testing Good Practices and Horrible MistakesRoy Osherove on Unit Testing Good Practices and Horrible Mistakes
Roy Osherove on Unit Testing Good Practices and Horrible Mistakes
 
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
 
Working Effectively with Legacy Code
Working Effectively with Legacy CodeWorking Effectively with Legacy Code
Working Effectively with Legacy Code
 
Unit Testing Fundamentals
Unit Testing FundamentalsUnit Testing Fundamentals
Unit Testing Fundamentals
 
Test-Driven Development (TDD)
Test-Driven Development (TDD)Test-Driven Development (TDD)
Test-Driven Development (TDD)
 
Implementing Quality on a Java Project
Implementing Quality on a Java ProjectImplementing Quality on a Java Project
Implementing Quality on a Java Project
 

Viewers also liked

Jonathan 20mayo (1)
Jonathan  20mayo (1)Jonathan  20mayo (1)
Jonathan 20mayo (1)cris03glu
 
Project 3 residential landscape project march 2015
Project 3 residential landscape project march 2015Project 3 residential landscape project march 2015
Project 3 residential landscape project march 2015
siewhui28
 
IT Career PowerPoint Template
IT Career PowerPoint TemplateIT Career PowerPoint Template
IT Career PowerPoint Template
PoweredTemplate.com
 
Project 2 design process research & analysis mac 2015-4
Project 2 design process research & analysis mac 2015-4Project 2 design process research & analysis mac 2015-4
Project 2 design process research & analysis mac 2015-4
siewhui28
 
Outsourcing Best Practices Moscow, 11.03.09
Outsourcing Best Practices   Moscow, 11.03.09Outsourcing Best Practices   Moscow, 11.03.09
Outsourcing Best Practices Moscow, 11.03.09
Acotax Ltd
 
magazine
magazinemagazine
magazine
siewhui28
 
Project 1 integration march 2015
Project 1 integration march 2015Project 1 integration march 2015
Project 1 integration march 2015
siewhui28
 
Review on cost estimation technque for web application [part 1]
Review on cost estimation technque for web application [part 1]Review on cost estimation technque for web application [part 1]
Review on cost estimation technque for web application [part 1]
Sayed Mohsin Reza
 
Tarea de mkt online
Tarea de mkt onlineTarea de mkt online
Tarea de mkt online
pamelichi12
 
ICI
ICIICI
Debora d'Avila Reis Universidade das Crianças
Debora d'Avila Reis Universidade das CriançasDebora d'Avila Reis Universidade das Crianças
Debora d'Avila Reis Universidade das Crianças
eucunet
 
Business Sourcing Diagram for PowerPoint
Business Sourcing Diagram for PowerPointBusiness Sourcing Diagram for PowerPoint
Business Sourcing Diagram for PowerPoint
PoweredTemplate.com
 
Estimation - web software development estimation DrupalCon and DrupalCamp pre...
Estimation - web software development estimation DrupalCon and DrupalCamp pre...Estimation - web software development estimation DrupalCon and DrupalCamp pre...
Estimation - web software development estimation DrupalCon and DrupalCamp pre...
Andy Kucharski
 
3D Arrows
3D Arrows3D Arrows

Viewers also liked (18)

Jonathan 20mayo (1)
Jonathan  20mayo (1)Jonathan  20mayo (1)
Jonathan 20mayo (1)
 
Project 3 residential landscape project march 2015
Project 3 residential landscape project march 2015Project 3 residential landscape project march 2015
Project 3 residential landscape project march 2015
 
IT Career PowerPoint Template
IT Career PowerPoint TemplateIT Career PowerPoint Template
IT Career PowerPoint Template
 
Project 2 design process research & analysis mac 2015-4
Project 2 design process research & analysis mac 2015-4Project 2 design process research & analysis mac 2015-4
Project 2 design process research & analysis mac 2015-4
 
Outsourcing Best Practices Moscow, 11.03.09
Outsourcing Best Practices   Moscow, 11.03.09Outsourcing Best Practices   Moscow, 11.03.09
Outsourcing Best Practices Moscow, 11.03.09
 
magazine
magazinemagazine
magazine
 
Project 1 integration march 2015
Project 1 integration march 2015Project 1 integration march 2015
Project 1 integration march 2015
 
Review on cost estimation technque for web application [part 1]
Review on cost estimation technque for web application [part 1]Review on cost estimation technque for web application [part 1]
Review on cost estimation technque for web application [part 1]
 
Tarea de mkt online
Tarea de mkt onlineTarea de mkt online
Tarea de mkt online
 
ICI
ICIICI
ICI
 
Debora d'Avila Reis Universidade das Crianças
Debora d'Avila Reis Universidade das CriançasDebora d'Avila Reis Universidade das Crianças
Debora d'Avila Reis Universidade das Crianças
 
Business Sourcing Diagram for PowerPoint
Business Sourcing Diagram for PowerPointBusiness Sourcing Diagram for PowerPoint
Business Sourcing Diagram for PowerPoint
 
Estimation - web software development estimation DrupalCon and DrupalCamp pre...
Estimation - web software development estimation DrupalCon and DrupalCamp pre...Estimation - web software development estimation DrupalCon and DrupalCamp pre...
Estimation - web software development estimation DrupalCon and DrupalCamp pre...
 
Pinxos de fruita
Pinxos de fruitaPinxos de fruita
Pinxos de fruita
 
Pastisformatge
PastisformatgePastisformatge
Pastisformatge
 
Amanida
AmanidaAmanida
Amanida
 
Migues
MiguesMigues
Migues
 
3D Arrows
3D Arrows3D Arrows
3D Arrows
 

Similar to DotNet unit testing training

Software testing ... who’s responsible is it?
Software testing ... who’s responsible is it?Software testing ... who’s responsible is it?
Software testing ... who’s responsible is it?
Manjula03809891
 
Software testing ... who is responsible for it?
Software testing ... who is responsible for it?Software testing ... who is responsible for it?
Software testing ... who is responsible for it?
Manjula Piyumal
 
Introduction to test automation in java and php
Introduction to test automation in java and phpIntroduction to test automation in java and php
Introduction to test automation in java and phpTho Q Luong Luong
 
Embrace Unit Testing
Embrace Unit TestingEmbrace Unit Testing
Embrace Unit Testing
alessiopace
 
Python and test
Python and testPython and test
Python and test
Micron Technology
 
J Unit
J UnitJ Unit
Why Unit Testingl
Why Unit TestinglWhy Unit Testingl
Why Unit Testingl
priya_trivedi
 
Why unit testingl
Why unit testinglWhy unit testingl
Why unit testingl
Priya Sharma
 
Why Unit Testingl
Why Unit TestinglWhy Unit Testingl
Why Unit Testingl
priya_trivedi
 
A la découverte des google/test (aka gtest)
A la découverte des google/test (aka gtest)A la découverte des google/test (aka gtest)
A la découverte des google/test (aka gtest)
Thierry Gayet
 
Code igniter unittest-part1
Code igniter unittest-part1Code igniter unittest-part1
Code igniter unittest-part1
Albert Rosa
 
Test Driven Development (TDD) with FlexUnit 4 - 360|Flex San Jose preso
Test Driven Development (TDD) with FlexUnit 4 - 360|Flex San Jose presoTest Driven Development (TDD) with FlexUnit 4 - 360|Flex San Jose preso
Test Driven Development (TDD) with FlexUnit 4 - 360|Flex San Jose preso
Elad Elrom
 
Assessing Unit Test Quality
Assessing Unit Test QualityAssessing Unit Test Quality
Assessing Unit Test Qualityguest268ee8
 
Unit testing - A&BP CC
Unit testing - A&BP CCUnit testing - A&BP CC
Unit testing - A&BP CC
JWORKS powered by Ordina
 
Test & behavior driven development
Test & behavior driven developmentTest & behavior driven development
Test & behavior driven development
Tristan Libersat
 
Unit tests and TDD
Unit tests and TDDUnit tests and TDD
Unit tests and TDD
Roman Okolovich
 
Test Driven Development Introduction
Test Driven Development IntroductionTest Driven Development Introduction
Test Driven Development Introduction
Nguyen Hai
 
Stopping the Rot - Putting Legacy C++ Under Test
Stopping the Rot - Putting Legacy C++ Under TestStopping the Rot - Putting Legacy C++ Under Test
Stopping the Rot - Putting Legacy C++ Under Test
Seb Rose
 
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)
 

Similar to DotNet unit testing training (20)

Software testing ... who’s responsible is it?
Software testing ... who’s responsible is it?Software testing ... who’s responsible is it?
Software testing ... who’s responsible is it?
 
Software testing ... who is responsible for it?
Software testing ... who is responsible for it?Software testing ... who is responsible for it?
Software testing ... who is responsible for it?
 
Introduction to test automation in java and php
Introduction to test automation in java and phpIntroduction to test automation in java and php
Introduction to test automation in java and php
 
Embrace Unit Testing
Embrace Unit TestingEmbrace Unit Testing
Embrace Unit Testing
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Python and test
Python and testPython and test
Python and test
 
J Unit
J UnitJ Unit
J Unit
 
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
 
A la découverte des google/test (aka gtest)
A la découverte des google/test (aka gtest)A la découverte des google/test (aka gtest)
A la découverte des google/test (aka gtest)
 
Code igniter unittest-part1
Code igniter unittest-part1Code igniter unittest-part1
Code igniter unittest-part1
 
Test Driven Development (TDD) with FlexUnit 4 - 360|Flex San Jose preso
Test Driven Development (TDD) with FlexUnit 4 - 360|Flex San Jose presoTest Driven Development (TDD) with FlexUnit 4 - 360|Flex San Jose preso
Test Driven Development (TDD) with FlexUnit 4 - 360|Flex San Jose preso
 
Assessing Unit Test Quality
Assessing Unit Test QualityAssessing Unit Test Quality
Assessing Unit Test Quality
 
Unit testing - A&BP CC
Unit testing - A&BP CCUnit testing - A&BP CC
Unit testing - A&BP CC
 
Test & behavior driven development
Test & behavior driven developmentTest & behavior driven development
Test & behavior driven development
 
Unit tests and TDD
Unit tests and TDDUnit tests and TDD
Unit tests and TDD
 
Test Driven Development Introduction
Test Driven Development IntroductionTest Driven Development Introduction
Test Driven Development Introduction
 
Stopping the Rot - Putting Legacy C++ Under Test
Stopping the Rot - Putting Legacy C++ Under TestStopping the Rot - Putting Legacy C++ Under Test
Stopping the Rot - Putting Legacy C++ Under Test
 
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
 

Recently uploaded

PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
g2nightmarescribd
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 

Recently uploaded (20)

PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 

DotNet unit testing training

  • 1. .NET Unit Test Session Prepared By: Tom Tang tomang0406@gmail.com Dec. 2010 (v1.0)
  • 4. Concept ●Why unit test? oPrevent side-effect as less as possible. oImprove code quality and stability. oImprove maintainability. oConsolidate design. oSave time from manual testing in the future. oDescribe the usage of your libraries and classes.
  • 5. Concept ●How unit test help our code quality? When you are doing implementation… oHow do you confirm your design “loosely-coupled” well enough? oHow do you keep the correct behavior of the class you’re updating? oHow do you ensure you have fixed the bug? oHow do you describe some tricky design / use case? ●Key rule: Cut off all dependency!!! 1.Human interaction dependency(UI) 2.Library dependency 3.Sequence dependency 4.Environment dependency 5.Hierarchy dependency
  • 6. Concept ●Cost - You must pay, then gain… oWrite code to verify code: More code, more bug. oCost much more time than real functional implementation. oMuch more code have to be maintained. Exchange short-term effort for long-term benefit.
  • 7. Concept ●Mind construction: oDo not think coverage, JUST DO IT®. oTest case shall keep growing, never think approach all at one time. oIt saves the future, not save the present. oDoing unit test is never easy, so it make quality competitive. There’s no silver bullet.
  • 9. Implementation Introduce Visual Studio built-in unit test tool:
  • 10. Implementation Best practice policy: 1.Every public entry must have at least 1 unit test case. 2.Pair programming technique – One implement test case, the other one implement functionality. 3.TDD (Not DDT) – Test-Driven Development – Implement test case before implement functional code.
  • 11. Implementation TDD life-cycle: Define interface (empty class) Write test code through the interface Test Failure. Implement functional class. Pass test case Commit Developer A Developer B
  • 12. Implementation Unit test running life-cycle for a class: ClassInitialize TestInitialize TestMethod TestCleanup ClassCleanup TestInitialize TestMethod TestCleanup
  • 13. Implementation How to do a useful test case: ●Awful, but at least it prevents run-time exception in some case. ●Better one:
  • 14. Implementation How to do a useful test case: ●Is this one good idea? Better to avoid this style, keep the meaning of “unit” in mind.
  • 15. Implementation How to do a useful test case: The other bad sample… Some genius developer write a perfect bug-free implementation, how come it failed to pass test case: ??
  • 16. Implementation How to do a useful test case: The other bad sample… Updating test case assume there’s an existing member… After running the creating test case, the updating test case passed. There’s a test case sequential dependency. Once a test case can’t be executed alone, it’s NOT an unit test case.
  • 17. Implementation How to do a useful test case: How to make the case better… Preparing its own precondition is every unit test case’s “Ownership”!
  • 18. Implementation How to do a useful test case: How to test error handling… FunSpec: Once user try to create duplicated member, we shall throw exception to alert user.
  • 19. Implementation How to do a useful test case: How to follow up? 1.Don’t do new unit-test case by only coverage reason. 2.Build new test case by JIRA Ticket.
  • 20. Implementation Ticket unit test life-cycle: Got ticket Write test code to reproduce the case Test Failure. Fix the bug. Pass test case Commit QA verify
  • 21. Implementation Ticket unit test life-cycle: ●Example – PMO-3357
  • 22. Implementation Ticket unit test life-cycle: ●Example – PMO-3357
  • 25. CHALLENGE Tricky technique to cut-off dependency
  • 26. Challenge How to cut-off dependency? Use MVC design to separate logic and UI private void OnButtonClick(EventArg e) { if (txtBox1.Text == “ABC”) { txtAnswer.Text = “XXX”; } else if (txtBox1.Text == “DEF”) { txtAnswer.Text = “YYY”; } } Change code design like this: private void OnButtonClick(EventArg e) { txtAnswer.Text = new Controller().GetAnswer(txtText1.Text); } // controller class can be unit tested. public class Controller { public string GetAnswer(string input) { if (input == “ABC”) { return “XXX”; } else if (input == “DEF”) { return “YYY”; } } }
  • 27. Challenge How to cut-off dependency? Library dependency: You want to test “ClassA”, but “ClassA” associated with “ClassB”, and you don’t want to involve “ClassB” in this test case. public class MathTool { public int AddNumber(int a, int b) { BackendService service = new BackendService(); // Dependency happen here. return service.AddNumberWebservice(a, b); } } public class BackendService { public int AddNumberWebservice(int a, int b) { HttpClient client = new HttpClient(); client.Url = "http://LiveMathTeacher.spi/AddNumber.asmx"; client.SubmitData(a, b); int c = (int)client.GetResponseData(); return c; } }
  • 28. Challenge public class BackendService : IService { public int AddNumberWebservice(int a, int b) { HttpClient client = new HttpClient(); client.Url = "http://LiveMathTeacher.spi/AddNumber.asmx"; client.SubmitData(a, b); int c = (int)client.GetResponseData(); return c; } } public class MockService : IService { public int AddNumberWebservice(int a, int b) { return a + b; } }
  • 29. Challenge How to cut-off dependency? Environment Dependency: ●If your class must access environment resource, like container(IIS)… public string GetLoginUserName() { if (CheckToken((string)Request[“token”])) // It accesses HTTP request resource return (string)Session[“UserName”]; // It accesses IIS memory } Encapsulate those resource into tool classes: public class SessionManager { #if(UNIT_TEST) // Use Dictionary structure to replace Session in unit-test public static Dictionary<string, object> Session = new Dictionary<string, object>(); #else public static HttpSessionState Session = HttpContext.Current.Session; #endif } Use similar class for switching: public string GetLoginUserName() { if (CheckToken((string)RequestManager.Request[“token”])) return (string)SessionManager.Session[“UserName”]; }
  • 30. Challenge How to cut-off dependency? Hierarchy Dependency: ●If your class inherits from the other class which you don’t have source(3rd party library…etc) and the base class would access any other dependency that you can’t cut-off… Examples: // This class inherits from System.ServiceProcess.ServiceBase, its constructor will auto access environment resource. using System.ServiceProcess; public class MyService : ServiceBase { } // This class inherits from System.Web.UI.Page, it’s ASP.NET class and access IIS resource. using System.Web.UI; public class MyPage : Page { }
  • 32. AUTOMATION - HUDSON Unit test with automation
  • 33. Automation - hudson Integrate unit test with Hudson: Visit this URL for sample: http://xxx.xxx.xxx/view/banana%20DEV/job/backend.UnitTest/
  • 34. Automation - hudson Integrate unit test with Hudson:
  • 35. Automation - hudson Integrate unit test with Hudson:
  • 37. Professional guideline Extract the summary from the book “Pragmatic Unit Test”: General Principles: 1.Test anything that might break 2.Test everything that does break 3.New code is guilty until proven innocent 4.Write at least as much test code as production code 5.Run local tests with each compile 6.Run all tests before check-in to repository Questions to Ask: 1.If the code ran correctly, how would I know? 2.How am I going to test this? 3.What else can go wrong? 4.Could this same kind of problem happen anywhere else?
  • 38. Professional guide line Extract the summary from the book “Pragmatic Unit Test”: What to Test: Use Your RIGHT-BICEP 1.Are the results right? 2.Are all the boundary conditions CORRECT? 3.Can you check inverse relationships? 4.Can you cross-check results using other means? 5.Can you force error conditions to happen? 6.Are performance characteristics within bounds? Good tests are A TRIP 1.Automatic 2.Thorough 3.Repeatable 4.Independent 5.Professional
  • 39. Professional guide line Extract the summary from the book “Pragmatic Unit Test”: CORRECT Boundary Conditions 1.Conformance - Does the value conform to an expected format? 2.Ordering - Is the set of values ordered or unordered as appropriate? 3.Range - Is the value within reasonable minimum and maximum values? 4.Reference - Does the code reference anything external that isn‘t under direct control of the code itself? 5.Existence - Does the value exist? (e.g., is non-null, non-zero, present in a set, etc.) 6.Cardinality - Are there exactly enough values? 7.Time (absolute and relative) - Is everything happening in order? At the right time? In time?
  • 40. Q & A AND SHARING How to configure Strawberry

Editor's Notes

  1. In object-orient design, ideally we purchase “loosely-coupled” design. How do you confirm your design “loosely-coupled” well enough? By unit test. If it’s hard to implement unit test on your class, it indicate your class design is not “loosely-coupled”.
  2. In object-orient design, ideally we purchase “loosely-coupled” design. How do you confirm your design “loosely-coupled” well enough? By unit test. If it’s hard to implement unit test on your class, it indicate your class design is not “loosely-coupled”. Due to unit test can’t test GUI or any human manually operation, this limit force you do MVC( Model / View / Control ) design! Prevent QA reopen regression bug. Every ticket should have a test case to reproduce it, then try to pass it. Every test case show how to use this class or method by outside respect. Dependency: Human interaction dependency(UI) – By MVC design Library dependency Sequence dependency Environment dependency Hierarchy dependency
  3. After you know the cost and price to involve one methodology, you must have some mind preparation. Everything has a balance decision, we shall figure out what the balance is, this is trade-off. “If you always think a cheaper way, easy way to do anything, then you shall get cheaper salary and easy pay by that.” “Keep your doing and thinking in valuable way, then you will get valuable salary.”
  4. See the video demo.
  5. DDT can kill bugs, I think TDD can do it also. 
  6. ClassInitialize: Initial some important precondition to make all test cases runnable by class level: Like some static resource initialization, database connection establish…etc. TestInitialize: Restore testing data / materials, precondition as well. TestMethod: Your test case TestCleanup: Clean up any result generated by the test case. ClassCleanup: Release some static resource, clean up legacy data as well.
  7. We assume SQLHelper has been initialized in “ClassInitialize”. All legacy data has been clean up in “TestInitialize”
  8. It actually mixes 2 method test into 1, and it made the test case has dependency to the other method which is not our primary test target. Once this case is failure, not easy to clarify
  9. Why???
  10. What’s ownership? It’s ownership.
  11. What’s ownership? It’s ownership.
  12. After we bulild up general test case, how to follow up?