SlideShare a Scribd company logo
1 of 24
Download to read offline
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

What's hot

What's hot (20)

Advance unittest
Advance unittestAdvance unittest
Advance unittest
 
TestNG vs Junit
TestNG vs JunitTestNG vs Junit
TestNG vs Junit
 
Power mock
Power mockPower mock
Power mock
 
05 junit
05 junit05 junit
05 junit
 
Test driven development - JUnit basics and best practices
Test driven development - JUnit basics and best practicesTest driven development - JUnit basics and best practices
Test driven development - JUnit basics and best practices
 
Workshop unit test
Workshop   unit testWorkshop   unit test
Workshop unit test
 
Simple Unit Testing With Netbeans 6.1
Simple Unit Testing With Netbeans 6.1Simple Unit Testing With Netbeans 6.1
Simple Unit Testing With Netbeans 6.1
 
Best practices unit testing
Best practices unit testing Best practices unit testing
Best practices unit testing
 
JMockit Framework Overview
JMockit Framework OverviewJMockit Framework Overview
JMockit Framework Overview
 
Java Unit Testing
Java Unit TestingJava Unit Testing
Java Unit Testing
 
JUnit 5
JUnit 5JUnit 5
JUnit 5
 
Grails Spock Testing
Grails Spock TestingGrails Spock Testing
Grails Spock Testing
 
Junit
JunitJunit
Junit
 
Tdd & unit test
Tdd & unit testTdd & unit test
Tdd & unit test
 
JUnit 4
JUnit 4JUnit 4
JUnit 4
 
Testing with Junit4
Testing with Junit4Testing with Junit4
Testing with Junit4
 
Unit test-using-spock in Grails
Unit test-using-spock in GrailsUnit test-using-spock in Grails
Unit test-using-spock in Grails
 
Unit testing with JUnit
Unit testing with JUnitUnit testing with JUnit
Unit testing with JUnit
 
New Features Of Test Unit 2.x
New Features Of Test Unit 2.xNew Features Of Test Unit 2.x
New Features Of Test Unit 2.x
 
Unit Testing with JUnit4 by Ravikiran Janardhana
Unit Testing with JUnit4 by Ravikiran JanardhanaUnit Testing with JUnit4 by Ravikiran Janardhana
Unit Testing with JUnit4 by Ravikiran Janardhana
 

Viewers also liked

How to improve your unit tests?
How to improve your unit tests?How to improve your unit tests?
How to improve your unit tests?Péter Módos
 
Database Unit Testing Made Easy with VSTS
Database Unit Testing Made Easy with VSTSDatabase Unit Testing Made Easy with VSTS
Database Unit Testing Made Easy with VSTSSanil Mhatre
 
Efficient JavaScript Unit Testing, JavaOne China 2013
Efficient JavaScript Unit Testing, JavaOne China 2013Efficient JavaScript Unit Testing, JavaOne China 2013
Efficient JavaScript Unit Testing, JavaOne China 2013Hazem Saleh
 
Unit testing JavaScript using Mocha and Node
Unit testing JavaScript using Mocha and NodeUnit testing JavaScript using Mocha and Node
Unit testing JavaScript using Mocha and NodeJosh Mock
 
An Introduction to Unit Testing
An Introduction to Unit TestingAn Introduction to Unit Testing
An Introduction to Unit TestingJoe Tremblay
 
JUnit- A Unit Testing Framework
JUnit- A Unit Testing FrameworkJUnit- A Unit Testing Framework
JUnit- A Unit Testing FrameworkOnkar Deshpande
 
Unit testing of spark applications
Unit testing of spark applicationsUnit testing of spark applications
Unit testing of spark applicationsKnoldus Inc.
 
UNIT TESTING PPT
UNIT TESTING PPTUNIT TESTING PPT
UNIT TESTING PPTsuhasreddy1
 

Viewers also liked (11)

How to improve your unit tests?
How to improve your unit tests?How to improve your unit tests?
How to improve your unit tests?
 
Database Unit Testing Made Easy with VSTS
Database Unit Testing Made Easy with VSTSDatabase Unit Testing Made Easy with VSTS
Database Unit Testing Made Easy with VSTS
 
Unit Testing SQL Server
Unit Testing SQL ServerUnit Testing SQL Server
Unit Testing SQL Server
 
Efficient JavaScript Unit Testing, JavaOne China 2013
Efficient JavaScript Unit Testing, JavaOne China 2013Efficient JavaScript Unit Testing, JavaOne China 2013
Efficient JavaScript Unit Testing, JavaOne China 2013
 
Unit testing JavaScript using Mocha and Node
Unit testing JavaScript using Mocha and NodeUnit testing JavaScript using Mocha and Node
Unit testing JavaScript using Mocha and Node
 
An Introduction to Unit Testing
An Introduction to Unit TestingAn Introduction to Unit Testing
An Introduction to Unit Testing
 
JUnit- A Unit Testing Framework
JUnit- A Unit Testing FrameworkJUnit- A Unit Testing Framework
JUnit- A Unit Testing Framework
 
Unit testing of spark applications
Unit testing of spark applicationsUnit testing of spark applications
Unit testing of spark applications
 
Introduction to White box testing
Introduction to White box testingIntroduction to White box testing
Introduction to White box testing
 
UNIT TESTING PPT
UNIT TESTING PPTUNIT TESTING PPT
UNIT TESTING PPT
 
Software Testing
Software TestingSoftware Testing
Software Testing
 

Similar to Unit testing 101

We Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End DevelopmentWe Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End DevelopmentAll Things Open
 
Junit mockito and PowerMock in Java
Junit mockito and  PowerMock in JavaJunit mockito and  PowerMock in Java
Junit mockito and PowerMock in JavaAnkur Maheshwari
 
Effective Unit Test Style Guide
Effective Unit Test Style GuideEffective Unit Test Style Guide
Effective Unit Test Style GuideJacky Lai
 
Testing And Drupal
Testing And DrupalTesting And Drupal
Testing And DrupalPeter Arato
 
An Introduction To Unit Testing and TDD
An Introduction To Unit Testing and TDDAn Introduction To Unit Testing and TDD
An Introduction To Unit Testing and TDDAhmed Ehab AbdulAziz
 
Java Unit Test - JUnit
Java Unit Test - JUnitJava Unit Test - JUnit
Java Unit Test - JUnitAktuğ Urun
 
An introduction to unit testing
An introduction to unit testingAn introduction to unit testing
An introduction to unit testingAdam Stephensen
 
Android testing
Android testingAndroid testing
Android testingSean Tsai
 
Software Engineering - RS3
Software Engineering - RS3Software Engineering - RS3
Software Engineering - RS3AtakanAral
 
Introduction to JUnit testing in OpenDaylight
Introduction to JUnit testing in OpenDaylightIntroduction to JUnit testing in OpenDaylight
Introduction to JUnit testing in OpenDaylightOpenDaylight
 
Testing with VS2010 - A Bugs Life
Testing with VS2010 - A Bugs LifeTesting with VS2010 - A Bugs Life
Testing with VS2010 - A Bugs LifePeter Gfader
 

Similar to Unit testing 101 (20)

We Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End DevelopmentWe Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End Development
 
Junit mockito and PowerMock in Java
Junit mockito and  PowerMock in JavaJunit mockito and  PowerMock in Java
Junit mockito and PowerMock in Java
 
Unit Testing in Java
Unit Testing in JavaUnit Testing in Java
Unit Testing in Java
 
Effective Unit Test Style Guide
Effective Unit Test Style GuideEffective Unit Test Style Guide
Effective Unit Test Style Guide
 
Testing And Drupal
Testing And DrupalTesting And Drupal
Testing And Drupal
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
Mocking with Mockito
Mocking with MockitoMocking with Mockito
Mocking with Mockito
 
An Introduction To Unit Testing and TDD
An Introduction To Unit Testing and TDDAn Introduction To Unit Testing and TDD
An Introduction To Unit Testing and TDD
 
Java Unit Test - JUnit
Java Unit Test - JUnitJava Unit Test - JUnit
Java Unit Test - JUnit
 
An introduction to unit testing
An introduction to unit testingAn introduction to unit testing
An introduction to unit testing
 
Unit testing basic
Unit testing basicUnit testing basic
Unit testing basic
 
Android testing
Android testingAndroid testing
Android testing
 
Software Engineering - RS3
Software Engineering - RS3Software Engineering - RS3
Software Engineering - RS3
 
Introduction to JUnit testing in OpenDaylight
Introduction to JUnit testing in OpenDaylightIntroduction to JUnit testing in OpenDaylight
Introduction to JUnit testing in OpenDaylight
 
Junit
JunitJunit
Junit
 
Test driven development
Test driven developmentTest driven development
Test driven development
 
Junit and testNG
Junit and testNGJunit and testNG
Junit and testNG
 
Unit testing - A&BP CC
Unit testing - A&BP CCUnit testing - A&BP CC
Unit testing - A&BP CC
 
Testing with VS2010 - A Bugs Life
Testing with VS2010 - A Bugs LifeTesting with VS2010 - A Bugs Life
Testing with VS2010 - A Bugs Life
 
Junit_.pptx
Junit_.pptxJunit_.pptx
Junit_.pptx
 

Recently uploaded

Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...AliaaTarek5
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditSkynet Technologies
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Scott Andery
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 

Recently uploaded (20)

Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance Audit
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 

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)