SlideShare a Scribd company logo
1 of 18
Unit Testing Basics
Stanislav Tyurikov
Unit Test definition
Unit Test verifies the behavior of small elements in a software
system, which are most often a single class or method. Every UT
must have several characteristics (F.I.R.S.T.):
• Fast
takes a little time to execute (less than 0,01 sec).
• Isolated
does not interact with over parts of a system, failure reasons become obvious.
• Repeatable
run repeatedly in any order, any time.
• Self-Checking
no manual evaluation required.
• Timely
written before the code.
Types of tests
Unit Test Component Test System Test Functional Test
Also known as Integration Test Acceptance Test
Depends on
Execution Time ms sec min hour
Description
Check class,
method
Test component
integrity, DB
queries.
System API (WS,
JNDI, etc), external
client interaction
Customer oriented.
Use UI controls,
pages, links, etc.
execution order
Each kind of test has its own area of responsibility, setup efforts, and accordingly,
different execution time.
What Unit Test is not?
Test is not a unit if:
• Interacts with over parts of the system (DB, WS, FS, etc.).
• Takes to much time to run (more than 0,01 sec).
• Requires manual setup or verification.
Unit Test benefits
Correctly organized and well designed unit tests give
developers several benefits:
• Unit test as documentation.
• Unit test as safety net.
• Defect localization.
• Needless of debugging.
• Design improving.
Ineffective Unit Test
When does test become a problem, not a solution?
• Fragile Test – break too often.
• Erratic Test – sometimes it pass and sometimes it fail.
• Manual Intervention – a test requires a person to perform
some manual action each time it is run.
• Obscure Test – it is difficult to understand the test.
• Slow Test – test takes too much time to run.
Principles of Test Automation
• Write the Tests First
• Design for Testability
• Use the Front Door First
• Don’t Modify the SUT
• Keep Tests Independent
• Isolate the SUT
• Minimize Test Overlap
• Minimize Untestable Code
• Keep Test Logic Out of Production Code
• Verify One Condition per Test
• Ensure Commensurate Effort and Responsibility
How to start testing?
For new code: Test Driven Development (aka Test First).
If you have to add/modify feature on legacy code:
• Identify change points
Find places where you need to make your changes depend sensitively on your
architecture.
• Find test points
Find places where to write tests is easy.
• Break dependencies.
Make sure you can replace dependencies with stub/mock.
• Write test.
Implement test logic which reflects new requirements.
• Refactor.
Remove code duplication and smells.
Four-phase test execution
setup
execution
verification
teardown
FixtureSUT
Unit Test
Terminology:
• SUT – software under test.
• Fixture – SUTs dependencies (environment).
Phases:
• Setup: create/find SUT or Fixture.
• Execution: execute something on SUT.
• Verification: Verify state or behavior of SUT/Fixture.
• Teardown: clean up after test.
Simple Unit Test example
public class Statistics
{
public static double average(double[] data)
{
if (isEmpty(data)) {
throw new
IllegalArgumentException("Data mustn't be empty.");
}
return calculateAverage(data);
}
private static double calculateAverage(double[] data)
{
double sum = 0;
for (int i = 0; i < data.length; i++) {
sum += data[i];
}
return sum / data.length;
}
private static boolean isEmpty(double[] data)
{
return data == null || data.length == 0;
}
}
import org.testng.Assert;
import org.testng.annotations.Test;
public class StatisticsTest
{
@Test
public void average()
{
final double[] data = {1, 2, 3, 4};
final double expected = 2.5;
final double result = Statistics.average(data);
Assert.assertEquals(expected, result);
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void averageForNullData()
{
Statistics.average(null);
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void averageForEmptyData()
{
Statistics.average(new double[]{});
}
}
Class to test: Test:
State verification
State verification almost used to:
• Verify returned value.
• Verify state of the SUT (Front Door).
• Verify state of the Fixture (Back Door).
Behavior verification & Test Doubles
Behavior verification used to check SUT correctly calls it’s
fixture. General idea is replace fixture with test doubles (spies
or mock objects) and check them after test execution. Behavior
verification usually used when SUT is stateless.
Test Spy – collects information about method calls. For
example, count of specific method executions.
Mock Object – record some scenario (order and count of
method calls), which must be reproduced on the execution
phase. Checks itself on the verification phase.
EasyMock Framework
EasyMock framework help us to create different kinds of test doubles. We
can create double for an interface and class as well.
Simple stubbing example:
import org.easymock.EasyMock;
import org.testng.Assert;
import org.testng.annotations.Test;
interface DataSource
{
String[] getData();
}
public class StubExample
{
@Test
public void createStubByInterface()
{
final String[] dataToReturnByStub = {"value1", "value2"};
final DataSource dataSource = EasyMock.createMock(DataSource.class);
EasyMock.expect(dataSource.getData()).andStubReturn(dataToReturnByStub);
EasyMock.replay(dataSource);
Assert.assertEquals(dataSource.getData(), dataToReturnByStub);
}
}
More information on http://easymock.org/
Behavior verification example with EasyMock
public class Application
{
private IReportBuilder reportBuilder;
private IEmployeeStatisticService statisticService;
public Application(IReportBuilder reportBuilder, IEmployeeStatisticService statisticService)
{
this.reportBuilder = reportBuilder;
this.statisticService = statisticService;
}
/**
* The execution flow of this operation is:
* 1) Get statistics report data.
* 2) Render report to a file specified.
* @param fileName
*/
public void buildSalaryReport(Writer writer)
{
final Map reportData = statisticService.createSalaryReportModel();
reportBuilder.renderReport(reportData, writer);
}
}
Class to test:
Behavior verification example with EasyMock
import org.easymock.EasyMock;
public class ApplicationTest
{
private IReportBuilder createReportBuilderMock(Writer writerMock)
{
final IReportBuilder reportBuilderMock = EasyMock.createMock(IReportBuilder.class);
reportBuilderMock.renderReport(EasyMock.anyObject(Map.class), EasyMock.eq(writerMock));
EasyMock.expectLastCall();
return reportBuilderMock;
}
private IEmployeeStatisticService createEmployeeStatisticServiceMock()
{
final Map<String, Object> mockReturn = new HashMap<String, Object>();
final IEmployeeStatisticService employeeStatisticServiceMock = EasyMock.createMock(IEmployeeStatisticService.class);
EasyMock.expect(employeeStatisticServiceMock.createSalaryReportModel()).andStubReturn(mockReturn);
return employeeStatisticServiceMock;
}
private Writer createWriterMock()
{
final Writer writerMock = EasyMock.createMock(Writer.class);
return writerMock;
}
. . .
}
Mock setup methods:
Behavior verification example with EasyMock
import org.easymock.EasyMock;
import org.testng.annotations.Test;
public class ApplicationTest
{
. . .
@Test
public void applicationFlow()
{
// setup fixture
final Writer writerMock = createWriterMock();
final IEmployeeStatisticService employeeStatisticServiceMock = createEmployeeStatisticServiceMock();
final IReportBuilder reportBuilderMock = createeReportBuilderMock(writerMock);
EasyMock.replay(reportBuilderMock, employeeStatisticServiceMock, writerMock);
// setup CUT.
final Application application =
new Application(reportBuilderMock, employeeStatisticServiceMock);
// execute test.
application.buildSalaryReport(writerMock);
// verify.
EasyMock.verify(reportBuilderMock, employeeStatisticServiceMock, writerMock);
}
}
Test method:
Basic Unit Test Antipatterns
The Liar
Excessive Setup
Giant
The Mockery
The Inspector
Generous Leftovers
The Local Hero (Hidden
Dependency)
The Nitpicker
The Secret Catcher
The Dodger
The Loudmouth
The Greedy Catcher
The Sequencer
The Enumerator
The Stranger
The Operating System
Evangelist
Success Against All Odds
The Free Ride
The One
The Peeping Tom
The Slow Poke
Links and resources
http://xunitpatterns.com/ - Testing patterns.
http://testng.org - TestNG framework home page.
http://easymock.org/ - EasyMock framework home page.
http://www.agiledata.org/essays/tdd.html - introduction to TDD methodology.
http://blog.james-carr.org/2006/11/03/tdd-anti-patterns/ - TDD anti-patterns.

More Related Content

What's hot

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 tests & TDD
Unit tests & TDDUnit tests & TDD
Unit tests & TDDDror Helper
 
Test Driven Development With Python
Test Driven Development With PythonTest Driven Development With Python
Test Driven Development With PythonSiddhi
 
UNIT TESTING PPT
UNIT TESTING PPTUNIT TESTING PPT
UNIT TESTING PPTsuhasreddy1
 
Keyword Driven Testing
Keyword Driven TestingKeyword Driven Testing
Keyword Driven TestingMaveryx
 
ISTQB, ISEB Lecture Notes- 4
ISTQB, ISEB Lecture Notes- 4ISTQB, ISEB Lecture Notes- 4
ISTQB, ISEB Lecture Notes- 4onsoftwaretest
 
TDD (Test Driven Design)
TDD (Test Driven Design)TDD (Test Driven Design)
TDD (Test Driven Design)nedirtv
 
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
 
Software testing.ppt
Software testing.pptSoftware testing.ppt
Software testing.pptKomal Garg
 
Unit testing best practices
Unit testing best practicesUnit testing best practices
Unit testing best practicesnickokiss
 
An Introduction to Test Driven Development
An Introduction to Test Driven Development An Introduction to Test Driven Development
An Introduction to Test Driven Development CodeOps Technologies LLP
 
Pruebas de software
Pruebas de softwarePruebas de software
Pruebas de softwareGomez Gomez
 
An introduction to unit testing
An introduction to unit testingAn introduction to unit testing
An introduction to unit testingAdam Stephensen
 
Java Multi Thead Programming
Java Multi Thead ProgrammingJava Multi Thead Programming
Java Multi Thead ProgrammingNishant Mevawala
 

What's hot (20)

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 tests & TDD
Unit tests & TDDUnit tests & TDD
Unit tests & TDD
 
Test Driven Development With Python
Test Driven Development With PythonTest Driven Development With Python
Test Driven Development With Python
 
UNIT TESTING PPT
UNIT TESTING PPTUNIT TESTING PPT
UNIT TESTING PPT
 
Keyword Driven Testing
Keyword Driven TestingKeyword Driven Testing
Keyword Driven Testing
 
Test design techniques
Test design techniquesTest design techniques
Test design techniques
 
ISTQB, ISEB Lecture Notes- 4
ISTQB, ISEB Lecture Notes- 4ISTQB, ISEB Lecture Notes- 4
ISTQB, ISEB Lecture Notes- 4
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
Unit testing
Unit testingUnit testing
Unit testing
 
Angular Unit Testing
Angular Unit TestingAngular Unit Testing
Angular Unit Testing
 
TDD (Test Driven Design)
TDD (Test Driven Design)TDD (Test Driven Design)
TDD (Test Driven Design)
 
Beginners - Get Started With Unit Testing in .NET
Beginners - Get Started With Unit Testing in .NETBeginners - Get Started With Unit Testing in .NET
Beginners - Get Started With Unit Testing in .NET
 
Software testing.ppt
Software testing.pptSoftware testing.ppt
Software testing.ppt
 
E2 e test with testcafe
E2 e test with testcafeE2 e test with testcafe
E2 e test with testcafe
 
Unit testing best practices
Unit testing best practicesUnit testing best practices
Unit testing best practices
 
An Introduction to Test Driven Development
An Introduction to Test Driven Development An Introduction to Test Driven Development
An Introduction to Test Driven Development
 
Pruebas de software
Pruebas de softwarePruebas de software
Pruebas de software
 
Software testing
Software testingSoftware testing
Software testing
 
An introduction to unit testing
An introduction to unit testingAn introduction to unit testing
An introduction to unit testing
 
Java Multi Thead Programming
Java Multi Thead ProgrammingJava Multi Thead Programming
Java Multi Thead Programming
 

Similar to Unit Testing

xUnit Style Database Testing
xUnit Style Database TestingxUnit Style Database Testing
xUnit Style Database TestingChris Oldwood
 
Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014
Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014
Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014FalafelSoftware
 
Breaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingBreaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingSteven Smith
 
API Performance Testing
API Performance TestingAPI Performance Testing
API Performance Testingrsg00usa
 
Some testing - Everything you should know about testing to go with @pedro_g_s...
Some testing - Everything you should know about testing to go with @pedro_g_s...Some testing - Everything you should know about testing to go with @pedro_g_s...
Some testing - Everything you should know about testing to go with @pedro_g_s...Sergio Arroyo
 
Qt test framework
Qt test frameworkQt test framework
Qt test frameworkICS
 
Testing with VS2010 - A Bugs Life
Testing with VS2010 - A Bugs LifeTesting with VS2010 - A Bugs Life
Testing with VS2010 - A Bugs LifePeter Gfader
 
Breaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingBreaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingSteven Smith
 
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...GlobalLogic Ukraine
 
Principles and patterns for test driven development
Principles and patterns for test driven developmentPrinciples and patterns for test driven development
Principles and patterns for test driven developmentStephen Fuqua
 
Building unit tests correctly with visual studio 2013
Building unit tests correctly with visual studio 2013Building unit tests correctly with visual studio 2013
Building unit tests correctly with visual studio 2013Dror Helper
 
Grails unit testing
Grails unit testingGrails unit testing
Grails unit testingpleeps
 
谷歌 Scott-lessons learned in testability
谷歌 Scott-lessons learned in testability谷歌 Scott-lessons learned in testability
谷歌 Scott-lessons learned in testabilitydrewz lin
 

Similar to Unit Testing (20)

xUnit Style Database Testing
xUnit Style Database TestingxUnit Style Database Testing
xUnit Style Database Testing
 
Unit testing
Unit testingUnit testing
Unit testing
 
Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014
Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014
Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014
 
Breaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingBreaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit Testing
 
Junit and testNG
Junit and testNGJunit and testNG
Junit and testNG
 
API Performance Testing
API Performance TestingAPI Performance Testing
API Performance Testing
 
Unit tests and TDD
Unit tests and TDDUnit tests and TDD
Unit tests and TDD
 
Some testing - Everything you should know about testing to go with @pedro_g_s...
Some testing - Everything you should know about testing to go with @pedro_g_s...Some testing - Everything you should know about testing to go with @pedro_g_s...
Some testing - Everything you should know about testing to go with @pedro_g_s...
 
Qt test framework
Qt test frameworkQt test framework
Qt test framework
 
Unit Tesing in iOS
Unit Tesing in iOSUnit Tesing in iOS
Unit Tesing in iOS
 
Testing with VS2010 - A Bugs Life
Testing with VS2010 - A Bugs LifeTesting with VS2010 - A Bugs Life
Testing with VS2010 - A Bugs Life
 
Test driven development
Test driven developmentTest driven development
Test driven development
 
Breaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingBreaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit Testing
 
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...
 
Principles and patterns for test driven development
Principles and patterns for test driven developmentPrinciples and patterns for test driven development
Principles and patterns for test driven development
 
Unit testing basic
Unit testing basicUnit testing basic
Unit testing basic
 
Building unit tests correctly with visual studio 2013
Building unit tests correctly with visual studio 2013Building unit tests correctly with visual studio 2013
Building unit tests correctly with visual studio 2013
 
Grails unit testing
Grails unit testingGrails unit testing
Grails unit testing
 
Unit testing basics
Unit testing basicsUnit testing basics
Unit testing basics
 
谷歌 Scott-lessons learned in testability
谷歌 Scott-lessons learned in testability谷歌 Scott-lessons learned in testability
谷歌 Scott-lessons learned in testability
 

Recently uploaded

Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
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
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
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
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 

Recently uploaded (20)

Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
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
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
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
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 

Unit Testing

  • 2. Unit Test definition Unit Test verifies the behavior of small elements in a software system, which are most often a single class or method. Every UT must have several characteristics (F.I.R.S.T.): • Fast takes a little time to execute (less than 0,01 sec). • Isolated does not interact with over parts of a system, failure reasons become obvious. • Repeatable run repeatedly in any order, any time. • Self-Checking no manual evaluation required. • Timely written before the code.
  • 3. Types of tests Unit Test Component Test System Test Functional Test Also known as Integration Test Acceptance Test Depends on Execution Time ms sec min hour Description Check class, method Test component integrity, DB queries. System API (WS, JNDI, etc), external client interaction Customer oriented. Use UI controls, pages, links, etc. execution order Each kind of test has its own area of responsibility, setup efforts, and accordingly, different execution time.
  • 4. What Unit Test is not? Test is not a unit if: • Interacts with over parts of the system (DB, WS, FS, etc.). • Takes to much time to run (more than 0,01 sec). • Requires manual setup or verification.
  • 5. Unit Test benefits Correctly organized and well designed unit tests give developers several benefits: • Unit test as documentation. • Unit test as safety net. • Defect localization. • Needless of debugging. • Design improving.
  • 6. Ineffective Unit Test When does test become a problem, not a solution? • Fragile Test – break too often. • Erratic Test – sometimes it pass and sometimes it fail. • Manual Intervention – a test requires a person to perform some manual action each time it is run. • Obscure Test – it is difficult to understand the test. • Slow Test – test takes too much time to run.
  • 7. Principles of Test Automation • Write the Tests First • Design for Testability • Use the Front Door First • Don’t Modify the SUT • Keep Tests Independent • Isolate the SUT • Minimize Test Overlap • Minimize Untestable Code • Keep Test Logic Out of Production Code • Verify One Condition per Test • Ensure Commensurate Effort and Responsibility
  • 8. How to start testing? For new code: Test Driven Development (aka Test First). If you have to add/modify feature on legacy code: • Identify change points Find places where you need to make your changes depend sensitively on your architecture. • Find test points Find places where to write tests is easy. • Break dependencies. Make sure you can replace dependencies with stub/mock. • Write test. Implement test logic which reflects new requirements. • Refactor. Remove code duplication and smells.
  • 9. Four-phase test execution setup execution verification teardown FixtureSUT Unit Test Terminology: • SUT – software under test. • Fixture – SUTs dependencies (environment). Phases: • Setup: create/find SUT or Fixture. • Execution: execute something on SUT. • Verification: Verify state or behavior of SUT/Fixture. • Teardown: clean up after test.
  • 10. Simple Unit Test example public class Statistics { public static double average(double[] data) { if (isEmpty(data)) { throw new IllegalArgumentException("Data mustn't be empty."); } return calculateAverage(data); } private static double calculateAverage(double[] data) { double sum = 0; for (int i = 0; i < data.length; i++) { sum += data[i]; } return sum / data.length; } private static boolean isEmpty(double[] data) { return data == null || data.length == 0; } } import org.testng.Assert; import org.testng.annotations.Test; public class StatisticsTest { @Test public void average() { final double[] data = {1, 2, 3, 4}; final double expected = 2.5; final double result = Statistics.average(data); Assert.assertEquals(expected, result); } @Test(expectedExceptions = IllegalArgumentException.class) public void averageForNullData() { Statistics.average(null); } @Test(expectedExceptions = IllegalArgumentException.class) public void averageForEmptyData() { Statistics.average(new double[]{}); } } Class to test: Test:
  • 11. State verification State verification almost used to: • Verify returned value. • Verify state of the SUT (Front Door). • Verify state of the Fixture (Back Door).
  • 12. Behavior verification & Test Doubles Behavior verification used to check SUT correctly calls it’s fixture. General idea is replace fixture with test doubles (spies or mock objects) and check them after test execution. Behavior verification usually used when SUT is stateless. Test Spy – collects information about method calls. For example, count of specific method executions. Mock Object – record some scenario (order and count of method calls), which must be reproduced on the execution phase. Checks itself on the verification phase.
  • 13. EasyMock Framework EasyMock framework help us to create different kinds of test doubles. We can create double for an interface and class as well. Simple stubbing example: import org.easymock.EasyMock; import org.testng.Assert; import org.testng.annotations.Test; interface DataSource { String[] getData(); } public class StubExample { @Test public void createStubByInterface() { final String[] dataToReturnByStub = {"value1", "value2"}; final DataSource dataSource = EasyMock.createMock(DataSource.class); EasyMock.expect(dataSource.getData()).andStubReturn(dataToReturnByStub); EasyMock.replay(dataSource); Assert.assertEquals(dataSource.getData(), dataToReturnByStub); } } More information on http://easymock.org/
  • 14. Behavior verification example with EasyMock public class Application { private IReportBuilder reportBuilder; private IEmployeeStatisticService statisticService; public Application(IReportBuilder reportBuilder, IEmployeeStatisticService statisticService) { this.reportBuilder = reportBuilder; this.statisticService = statisticService; } /** * The execution flow of this operation is: * 1) Get statistics report data. * 2) Render report to a file specified. * @param fileName */ public void buildSalaryReport(Writer writer) { final Map reportData = statisticService.createSalaryReportModel(); reportBuilder.renderReport(reportData, writer); } } Class to test:
  • 15. Behavior verification example with EasyMock import org.easymock.EasyMock; public class ApplicationTest { private IReportBuilder createReportBuilderMock(Writer writerMock) { final IReportBuilder reportBuilderMock = EasyMock.createMock(IReportBuilder.class); reportBuilderMock.renderReport(EasyMock.anyObject(Map.class), EasyMock.eq(writerMock)); EasyMock.expectLastCall(); return reportBuilderMock; } private IEmployeeStatisticService createEmployeeStatisticServiceMock() { final Map<String, Object> mockReturn = new HashMap<String, Object>(); final IEmployeeStatisticService employeeStatisticServiceMock = EasyMock.createMock(IEmployeeStatisticService.class); EasyMock.expect(employeeStatisticServiceMock.createSalaryReportModel()).andStubReturn(mockReturn); return employeeStatisticServiceMock; } private Writer createWriterMock() { final Writer writerMock = EasyMock.createMock(Writer.class); return writerMock; } . . . } Mock setup methods:
  • 16. Behavior verification example with EasyMock import org.easymock.EasyMock; import org.testng.annotations.Test; public class ApplicationTest { . . . @Test public void applicationFlow() { // setup fixture final Writer writerMock = createWriterMock(); final IEmployeeStatisticService employeeStatisticServiceMock = createEmployeeStatisticServiceMock(); final IReportBuilder reportBuilderMock = createeReportBuilderMock(writerMock); EasyMock.replay(reportBuilderMock, employeeStatisticServiceMock, writerMock); // setup CUT. final Application application = new Application(reportBuilderMock, employeeStatisticServiceMock); // execute test. application.buildSalaryReport(writerMock); // verify. EasyMock.verify(reportBuilderMock, employeeStatisticServiceMock, writerMock); } } Test method:
  • 17. Basic Unit Test Antipatterns The Liar Excessive Setup Giant The Mockery The Inspector Generous Leftovers The Local Hero (Hidden Dependency) The Nitpicker The Secret Catcher The Dodger The Loudmouth The Greedy Catcher The Sequencer The Enumerator The Stranger The Operating System Evangelist Success Against All Odds The Free Ride The One The Peeping Tom The Slow Poke
  • 18. Links and resources http://xunitpatterns.com/ - Testing patterns. http://testng.org - TestNG framework home page. http://easymock.org/ - EasyMock framework home page. http://www.agiledata.org/essays/tdd.html - introduction to TDD methodology. http://blog.james-carr.org/2006/11/03/tdd-anti-patterns/ - TDD anti-patterns.