SlideShare a Scribd company logo
Unit Testing 101
Intro to What, Why, How
Outline
1. What is unit testing?
a. what are units?
b. testing the future, TDD
2. Why do we unit test?
a. advantages
i. refactoring
ii. maintainability
3. How do we unit test?
a. Guidelines
b. Assertions
c. Isolations
d. Mocks vs Stubs
4. Related Stuff
What is Unit Testing?
Kent Beck introduced the term
legacy code: code without tests
What is Unit Testing
Unified Process
Requirements --> Use Cases, Scenarios
Scenarios -> Classes, relationships
classes(or functions in FP) are the units!
Classes -> Unit Tests
Why Unit Testing?
To fail when there is no harm to do so
the cost to fix a bug in different stages
did you think about that in advance?
To refactor code (you can still refactor without UT)
To test after development
Self documenting code (if you read them)
How to do?
● one test, one scenario
○ no conditional statements like
■ if, switch etc
○ also no loops if possible
■ if there are loops, tests must be broken into other
tests
● one test, one assertion
● isolated test, not depending on each
○ need dependency, use injection, not arbitrary tests
● do not handle exceptions
○ you can assert that an exception will be thrown,
though
● tests are not functions of time!
How to do?
when to add tests:
● before new classes/stories
● before fixing new bugs
○ preparing the test scenario
○ filling the gap
● before introducing new features
you can also write tests for the completed code
How to do
Unit Test Pattern:
AAA : Arrange - Act - Assert
An Example in JUnit
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration( {"file:test/test-
config.xml", "file:web/WEB-INF/application-
security.xml",
"file:test/test-dao.xml"} )
public class MobileUtilsTest {
@Autowired
private MobileUtils mobileUtils;
@Autowired
private BankDao bankDao;
An Example in JUnit
@Test
public void testGenerateOtp() throws
Exception {
Bank bank = bankDao.findByBin
("402940");
String otp = mobileUtils.generateOtp
(bank);
System.out.println(otp);
Assert.assertNotNull(otp);
}
An Example in JUnit
@Test(expected = NullPointerException.class)
public void testGenerateNullBankOtp() throws
Exception{
try{
Bank bank = null;
String otp = mobileUtils.generateOtp
(bank);
}
catch (Exception e){
throw e;
}
}
How to do
Assertions:
● use as many as possible different types of
assertions
○ assertThat, assertEquals, assertSame,
assertNotNull
○ junit's matchers
● assertion statements must be readable
○ self documenting tests
○ not assertEquals( result, false )
○ please do assertEquals( result, expectedResult )
How to do?
Isolation is important:
● database isolation
○ use a test db if possible
● web container isolation
○ use dependency injection if possible
■ otherwise it is kind of integration testing
● see spring integration testing
● dependency injection
○ provides class isolation
● web services (rest & SOAP)
○ use mocks or stubs
● properties (file and system)
How to do?
Automate the tests (otherwise they are
meaningless)
use tools like ant, maven
Better use Jenkins!
How to do?
If isolation is important, use mocks and stubs
○ mocks
■ use them when you have dependencies that
cannot be fulfilled by writing simple stubs
● for example, an interface containing many method
declarations
○ stubs
■ use them when you call inner methods to test the
unit, so you don't have to write inner mocks too
How to do?
Mocks vs Stubs:
mocks depend on behavior verification
while stubs depend on state verification
examples from Martin Fowler:
Stub example
public interface MailService {
public void send (Message msg);
}
public class MailServiceStub implements MailService {
private List<Message> messages = new
ArrayList<Message>();
public void send (Message msg) {
messages.add(msg);
}
public int numberSent() {
return messages.size();
}
}
Stub Example
class OrderStateTester...
public void testOrderSendsMailIfUnfilled()
{
Order order = new Order(TALISKER, 51);
MailServiceStub mailer = new
MailServiceStub();
order.setMailer(mailer);
order.fill(warehouse);
assertEquals(1, mailer.numberSent());
}
Mock Example
class OrderInteractionTester...
public void testOrderSendsMailIfUnfilled() {
Order order = new Order(TALISKER, 51);
Mock warehouse = mock(Warehouse.class);
Mock mailer = mock(MailService.class);
order.setMailer((MailService) mailer.proxy());
mailer.expects(once()).method("send");
warehouse.expects(once()).method("hasInventory")
.withAnyArguments()
.will(returnValue(false));
order.fill((Warehouse) warehouse.proxy());
//verify
warehouse.verify();
assertTrue(order.isFilled());
}
}
Mocks vs Stubs
it really is a decision for TDD
in mocks, you go outside in, one story at a time
usually start from UI
in stubs, you go middle out, also one story,
can begin from business objects
if your code is complete, use real objects,
whenever possible (better code coverage)
mockists vs classical
a comparison for TDD
classical tries to use the existing objects in
test
mockist tries to mock complicated stuff and
dependencies
For Existing Projects
begin
add tests
submit to vcs
keep tests in a separate folder/module
test both for success and failure
test the important features first
or just write tests at all
end
Relatives, Friends
Code coverage
Strive for 100%
For starters, each project must have 20%
remember the 20/80 rule
use tools like http://www.jetbrains.com/idea/features/code_coverage.html
Test Driven Development
basis for TDD, write unit tests first!
can try if you are starting a new project
Thank you
Questions? (other than why this presentation is
in English)

More Related Content

PPTX
PDF
Unit testing with Junit
PDF
All about unit testing using (power) mock
PPTX
J unit스터디슬라이드
PPTX
Introduction to JUnit
PPSX
PDF
Unit testing best practices with JUnit
PPS
JUnit Presentation
Unit testing with Junit
All about unit testing using (power) mock
J unit스터디슬라이드
Introduction to JUnit
Unit testing best practices with JUnit
JUnit Presentation

What's hot (20)

PPTX
Advance unittest
PPTX
TestNG vs Junit
PPTX
Power mock
PPT
05 junit
PDF
Test driven development - JUnit basics and best practices
PDF
Workshop unit test
PPT
Simple Unit Testing With Netbeans 6.1
PPTX
Best practices unit testing
PPT
JMockit Framework Overview
PPTX
Java Unit Testing
PDF
PPTX
Grails Spock Testing
PPT
PPTX
Tdd & unit test
PPT
JUnit 4
PPTX
Testing with Junit4
PDF
Unit test-using-spock in Grails
PDF
Unit testing with JUnit
PPT
New Features Of Test Unit 2.x
PPTX
Unit Testing with JUnit4 by Ravikiran Janardhana
Advance unittest
TestNG vs Junit
Power mock
05 junit
Test driven development - JUnit basics and best practices
Workshop unit test
Simple Unit Testing With Netbeans 6.1
Best practices unit testing
JMockit Framework Overview
Java Unit Testing
Grails Spock Testing
Tdd & unit test
JUnit 4
Testing with Junit4
Unit test-using-spock in Grails
Unit testing with JUnit
New Features Of Test Unit 2.x
Unit Testing with JUnit4 by Ravikiran Janardhana
Ad

Viewers also liked (11)

PDF
How to improve your unit tests?
PPTX
Database Unit Testing Made Easy with VSTS
PDF
Unit Testing SQL Server
PDF
Efficient JavaScript Unit Testing, JavaOne China 2013
PDF
Unit testing JavaScript using Mocha and Node
PPTX
An Introduction to Unit Testing
PPTX
JUnit- A Unit Testing Framework
PDF
Unit testing of spark applications
PPTX
Introduction to White box testing
PPTX
UNIT TESTING PPT
PPT
Software Testing
How to improve your unit tests?
Database Unit Testing Made Easy with VSTS
Unit Testing SQL Server
Efficient JavaScript Unit Testing, JavaOne China 2013
Unit testing JavaScript using Mocha and Node
An Introduction to Unit Testing
JUnit- A Unit Testing Framework
Unit testing of spark applications
Introduction to White box testing
UNIT TESTING PPT
Software Testing
Ad

Similar to Unit testing 101 (20)

PDF
Unit testing basic
PPTX
Test-Driven Development
PDF
The Art of Unit Testing Feedback
ODP
Embrace Unit Testing
PDF
An Introduction to Test Driven Development
PPTX
2016 10-04: tdd++: tdd made easier
PDF
Unit testing - An introduction
PPT
Unit Testing
PPTX
The Test way
PPTX
Skillwise Unit Testing
PPTX
Integration and Unit Testing in Java using Test Doubles like mocks and stubs
PDF
Test Drive Development
PPTX
Practical unit testing tips
PDF
Introduction to Unit Testing, BDD and Mocking using TestBox & MockBox at Adob...
PDF
How and what to unit test
PDF
Getting Started With Testing
PDF
Unit Testing
PPTX
Testing 101
PDF
Introduction to Unit Testing, BDD and Mocking using TestBox & MockBox at Into...
PPTX
Unit testing
Unit testing basic
Test-Driven Development
The Art of Unit Testing Feedback
Embrace Unit Testing
An Introduction to Test Driven Development
2016 10-04: tdd++: tdd made easier
Unit testing - An introduction
Unit Testing
The Test way
Skillwise Unit Testing
Integration and Unit Testing in Java using Test Doubles like mocks and stubs
Test Drive Development
Practical unit testing tips
Introduction to Unit Testing, BDD and Mocking using TestBox & MockBox at Adob...
How and what to unit test
Getting Started With Testing
Unit Testing
Testing 101
Introduction to Unit Testing, BDD and Mocking using TestBox & MockBox at Into...
Unit testing

Recently uploaded (20)

PPTX
MYSQL Presentation for SQL database connectivity
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Electronic commerce courselecture one. Pdf
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Approach and Philosophy of On baking technology
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
KodekX | Application Modernization Development
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Encapsulation theory and applications.pdf
PDF
cuic standard and advanced reporting.pdf
PDF
Empathic Computing: Creating Shared Understanding
MYSQL Presentation for SQL database connectivity
Dropbox Q2 2025 Financial Results & Investor Presentation
Electronic commerce courselecture one. Pdf
Understanding_Digital_Forensics_Presentation.pptx
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Spectral efficient network and resource selection model in 5G networks
Review of recent advances in non-invasive hemoglobin estimation
Approach and Philosophy of On baking technology
Network Security Unit 5.pdf for BCA BBA.
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Chapter 3 Spatial Domain Image Processing.pdf
KodekX | Application Modernization Development
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Digital-Transformation-Roadmap-for-Companies.pptx
Per capita expenditure prediction using model stacking based on satellite ima...
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Encapsulation theory and applications.pdf
cuic standard and advanced reporting.pdf
Empathic Computing: Creating Shared Understanding

Unit testing 101

  • 1. Unit Testing 101 Intro to What, Why, How
  • 2. Outline 1. What is unit testing? a. what are units? b. testing the future, TDD 2. Why do we unit test? a. advantages i. refactoring ii. maintainability 3. How do we unit test? a. Guidelines b. Assertions c. Isolations d. Mocks vs Stubs 4. Related Stuff
  • 3. What is Unit Testing? Kent Beck introduced the term legacy code: code without tests
  • 4. What is Unit Testing Unified Process Requirements --> Use Cases, Scenarios Scenarios -> Classes, relationships classes(or functions in FP) are the units! Classes -> Unit Tests
  • 5. Why Unit Testing? To fail when there is no harm to do so the cost to fix a bug in different stages did you think about that in advance? To refactor code (you can still refactor without UT) To test after development Self documenting code (if you read them)
  • 6. How to do? ● one test, one scenario ○ no conditional statements like ■ if, switch etc ○ also no loops if possible ■ if there are loops, tests must be broken into other tests ● one test, one assertion ● isolated test, not depending on each ○ need dependency, use injection, not arbitrary tests ● do not handle exceptions ○ you can assert that an exception will be thrown, though ● tests are not functions of time!
  • 7. How to do? when to add tests: ● before new classes/stories ● before fixing new bugs ○ preparing the test scenario ○ filling the gap ● before introducing new features you can also write tests for the completed code
  • 8. How to do Unit Test Pattern: AAA : Arrange - Act - Assert
  • 9. An Example in JUnit @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration( {"file:test/test- config.xml", "file:web/WEB-INF/application- security.xml", "file:test/test-dao.xml"} ) public class MobileUtilsTest { @Autowired private MobileUtils mobileUtils; @Autowired private BankDao bankDao;
  • 10. An Example in JUnit @Test public void testGenerateOtp() throws Exception { Bank bank = bankDao.findByBin ("402940"); String otp = mobileUtils.generateOtp (bank); System.out.println(otp); Assert.assertNotNull(otp); }
  • 11. An Example in JUnit @Test(expected = NullPointerException.class) public void testGenerateNullBankOtp() throws Exception{ try{ Bank bank = null; String otp = mobileUtils.generateOtp (bank); } catch (Exception e){ throw e; } }
  • 12. How to do Assertions: ● use as many as possible different types of assertions ○ assertThat, assertEquals, assertSame, assertNotNull ○ junit's matchers ● assertion statements must be readable ○ self documenting tests ○ not assertEquals( result, false ) ○ please do assertEquals( result, expectedResult )
  • 13. How to do? Isolation is important: ● database isolation ○ use a test db if possible ● web container isolation ○ use dependency injection if possible ■ otherwise it is kind of integration testing ● see spring integration testing ● dependency injection ○ provides class isolation ● web services (rest & SOAP) ○ use mocks or stubs ● properties (file and system)
  • 14. How to do? Automate the tests (otherwise they are meaningless) use tools like ant, maven Better use Jenkins!
  • 15. How to do? If isolation is important, use mocks and stubs ○ mocks ■ use them when you have dependencies that cannot be fulfilled by writing simple stubs ● for example, an interface containing many method declarations ○ stubs ■ use them when you call inner methods to test the unit, so you don't have to write inner mocks too
  • 16. How to do? Mocks vs Stubs: mocks depend on behavior verification while stubs depend on state verification examples from Martin Fowler:
  • 17. Stub example public interface MailService { public void send (Message msg); } public class MailServiceStub implements MailService { private List<Message> messages = new ArrayList<Message>(); public void send (Message msg) { messages.add(msg); } public int numberSent() { return messages.size(); } }
  • 18. Stub Example class OrderStateTester... public void testOrderSendsMailIfUnfilled() { Order order = new Order(TALISKER, 51); MailServiceStub mailer = new MailServiceStub(); order.setMailer(mailer); order.fill(warehouse); assertEquals(1, mailer.numberSent()); }
  • 19. Mock Example class OrderInteractionTester... public void testOrderSendsMailIfUnfilled() { Order order = new Order(TALISKER, 51); Mock warehouse = mock(Warehouse.class); Mock mailer = mock(MailService.class); order.setMailer((MailService) mailer.proxy()); mailer.expects(once()).method("send"); warehouse.expects(once()).method("hasInventory") .withAnyArguments() .will(returnValue(false)); order.fill((Warehouse) warehouse.proxy()); //verify warehouse.verify(); assertTrue(order.isFilled()); } }
  • 20. Mocks vs Stubs it really is a decision for TDD in mocks, you go outside in, one story at a time usually start from UI in stubs, you go middle out, also one story, can begin from business objects if your code is complete, use real objects, whenever possible (better code coverage)
  • 21. mockists vs classical a comparison for TDD classical tries to use the existing objects in test mockist tries to mock complicated stuff and dependencies
  • 22. For Existing Projects begin add tests submit to vcs keep tests in a separate folder/module test both for success and failure test the important features first or just write tests at all end
  • 23. Relatives, Friends Code coverage Strive for 100% For starters, each project must have 20% remember the 20/80 rule use tools like http://www.jetbrains.com/idea/features/code_coverage.html Test Driven Development basis for TDD, write unit tests first! can try if you are starting a new project
  • 24. Thank you Questions? (other than why this presentation is in English)