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 best practices
Unit testing best practicesUnit testing best practices
Unit testing best practices
nickokiss
 

What's hot (20)

Unit testing
Unit testingUnit testing
Unit testing
 
An introduction to unit testing
An introduction to unit testingAn introduction to unit testing
An introduction to unit testing
 
Unit Testing (C#)
Unit Testing (C#)Unit Testing (C#)
Unit Testing (C#)
 
Workshop unit test
Workshop   unit testWorkshop   unit test
Workshop unit test
 
Unit Tests And Automated Testing
Unit Tests And Automated TestingUnit Tests And Automated Testing
Unit Tests And Automated Testing
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
Unit testing
Unit testingUnit testing
Unit testing
 
Unit and integration Testing
Unit and integration TestingUnit and integration Testing
Unit and integration Testing
 
UNIT TESTING
UNIT TESTINGUNIT TESTING
UNIT TESTING
 
Unit testing
Unit testing Unit testing
Unit testing
 
JUNit Presentation
JUNit PresentationJUNit Presentation
JUNit Presentation
 
Unit testing with NUnit
Unit testing with NUnitUnit testing with NUnit
Unit testing with NUnit
 
Université du soir - TDD
Université du soir - TDDUniversité du soir - TDD
Université du soir - TDD
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
Unit testing best practices
Unit testing best practicesUnit testing best practices
Unit testing best practices
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
N Unit Presentation
N Unit PresentationN Unit Presentation
N Unit Presentation
 
software testing
 software testing software testing
software testing
 
05 junit
05 junit05 junit
05 junit
 
Junit 4.0
Junit 4.0Junit 4.0
Junit 4.0
 

Similar to Unit Testing

谷歌 Scott-lessons learned in testability
谷歌 Scott-lessons learned in testability谷歌 Scott-lessons learned in testability
谷歌 Scott-lessons learned in testability
drewz 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

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
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
vu2urc
 

Recently uploaded (20)

Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
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
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
[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
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
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
 
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
 

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.