SlideShare a Scribd company logo
1 of 27
Download to read offline
Test Driven
Development
“TDD  is  not  testing,  it  is  a  design  technique”.

Christoforos Nalmpantis
What is TDD
TDD is a style of development where:
• You maintain an exhaustive suite of Programmer Tests
• No code goes into production unless it has associated tests
• You write the tests first
• The tests determine what code you need to write
Red – Green - Refactor
1. Write a test that fails
RED

REFACTOR

3. Eliminate redundancy

GREEN

2. Make the code work
A sad misconception
Because of the name of TDD most inexperienced developers
believe it is testing. This leads to the following objections:
• Writing unit tests takes too much time.
• How  could  I  write  tests  first  if  I  don’t  know  what  it  does  yet?
• Unit tests won't catch all the bugs.
A sad misconception
In fact TDD is a design technique and our objections should be:
• Designing takes too much time.
• How could I design first if I don't know what it does yet?
• Designing won't catch all the bugs.
Traditional software development
•Requirements
•Design

•Implementation
•Testing
•Maintenance
TDD is Agile
“Agile”  means:
• Characterized by quickness, lightness, and ease of movement;
nimble.
• Mentally quick or alert

SCRUM

WORKING SOFTWARE

ADAPTABILITY
extreme programming

DAILY

TRANSPARENCY

UNITY

ITERATION

continuous

CRYSTAL

SIMPLICITY
RELEASE
Why TDD
Why TDD
• Ensures quality
• Keeps code clear, simple and testable
• Provides documentation for different team
members
• Repeatable tests
• Enables rapid change
Why TDD
“When  you  already  have  Tests that documents how your code
works  and  also  verifies  every  logical  units,  programmer’s  bugs  
are significantly reduced resulting more time coding, less time
debugging.”
“You  can  confidently refactor your production code without
worrying about breaking it, if you already have test code written,
it  acts  as  safety  net.”
“Tests  on  TDD  describe  the  behaviour of the code you are going
to write. So, tests provides better picture of specification than
documentation written on a paper because test runs.”
A Practical Guide - Refactoring
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•

•
•
•
•

public void init() {
setLayout();
initMovieList();
initMovieField();
initAddButton();
}
private void setLayout() {
getContentPane().setLayout(new FlowLayout());
}
private void initMovieList() {
movieList = new JList(getMovies();
JScrollPane scroller = new JScrollpane(movieList);
getContentPane().add(scroller);
}
private void initMovieField() {
movieField = new JTextField(16);
getContentPane().add(movieField);
}
private void initAddButton() {
addButton = new JButton(“Add”);
addButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
myEditor.add(movie.getText());
movieList.setListData(myEditor.getMovies());
}

});
getContentPane().add(addButton);
}

•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•

Public void init() {
getContentPane().setLayout(new FlowLayout());
movieList = new JList(myEditor.getMoviews());
JScrollPane scroller = new JScrollPane(movieList);
getContentPane().add(scroller);
movieField = new JTextField(16);
getContentPane().add(movieField);
addButton = new JButton(“Add”);
addButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
myEditor.add(movie.getText());
movieList.setListData(myEditor.getMovies());
}
});
getContentPane().add(addButton);
}
A Practical Guide - Refactoring
• Extract Method
When a method gets too long or the
logic is too complex to be easily
understood, part of it can be pulled out
into a method of its own.
A Practical Guide - Refactoring
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•

public class Employee {
//0-engineer, 1-salesman, 2-manager
private String departmentName() {
switch (employeeType ) {
case 0:
return  “Engineering”;
case 1:
return  “Sales”;
case 2:
return  “Management”;
default:
return  “Unknown”;
}
}
}

• abstract public class Employee {
•
Public abstract String
departmentName();
• }
• public class Engineer extends Employee {
•
Public String departmentName() {
•
Return  “Engineering”;
•
}
• }
• public class SalesMan extends Employee {
•
Public String departmentName() {
•
Return  “Sales”;
•
}
• }
• public class Manager extends Employee {
•
Public String departmentName() {
•
Return  “Management”;
•
}
• }
A Practical Guide - Refactoring
• Replace Conditional with
Polymorphism
When we find switch statements,
consider creating subclasses to handle
the different cases and get rid of the
switch.
A Practical Guide - Refactoring
•
•
•
•
•
•
•
•
•
•

public Money calculateTotal(){
Money subtotal = getSubtotal();
Money tax = getTaxableSubtotal().times(0.15);
Money total = subtotal.plus(tax);
Boolean qualifiesForDiscount = getSubtotal().asDouble()>100.0;
Money discount = qualifiesForDiscount
?subtotal.times(0.10)
:new Money(0.0);
return total.minus(discount);
}

• public Money calculateTotal(){
•
return getSubtotal().plus((getTaxableSubtotal().times(0.15)))
•
.minus((getSubtotal().asDouble()>100.0)
•
?(getSubtotal().times(0.10))
•
:0);
• }
A Practical Guide - Refactoring
• Introduce Explaining Variable
When we have a complex expression
that is difficult to understand, we can
extract parts of it and store the
intermediate results in well-named
temporary variables. This breaks the
expression into easy to understand
pieces, as well as making the overall
expression clearer.
A Practical Guide - Refactoring
• public int fib(int i) {
•
int result;
•
if(i == 0){
•
result = 0;
•
}else if (i <=2){
•
result = 1;
•
}else {
•
result = fib( i – 1) + fib(i -2);
•
}
•
return result;
• }

• public int fib( int i ){
•
If (i == 0)return 0;
•
If (i <= 2)return 1;
•
return fib(i – 1) + fib(i – 2);
• }
A Practical Guide - Refactoring
• Replace Nested Conditional with Guard
Clauses
Many people have been taught that a
method should have only a single exit
point. There is no reason for this, certainly
not at the expense of clarity. In a method
that should exit under multiple conditions,
this leads to complex, nested conditional
statements. A better, and much clearer
alternative is to use guard clauses to
return under those conditions.
A Practical Guide - Refactoring
•
•
•
•
•
•
•

Extract class
Extract interface
Replace Type Code with Subclasses
Form Template Method
Replace constructor with Factory method
Replace Inheritance with Delegation
Replace magic number with symbolic constant
A Practical Guide - JUnit
• JUnit is a Java tool that allows you to easily write tests.
• It  uses  Annotations  und  Reflection  (see  one  of  the  next
chapters). During execution JUnit runs methods like:
@Test public void ...()
• JUnit offers  assert-methods to formulate your test outcomes.
• Example:
assertEquals(5, model.getCurrentValue());
Here, the order is important: expected value, actual
value, since an error report says: expected 5 but was ...
A Practical Guide - JUnit
The Assertions
1. assertEquals(expected, actual)
2. assertEquals(expected, actual, delta) for
float  and double obligatory; checks if
|expected  −  actual|  <  δ
3. assertNull, assertNotNull
4. assertTrue, assertFalse
5. assertSame, assertNotSame
A Practical Guide - JUnit
Junit Life Cycle
1. JUnit collects all @Test-Methods in your test class via  Reflection.
2. JUnit executes these methods in isolation from each other, and with
undefined  order.
3. JUnit creates a new instance of the test class for each test run
in  order  to  avoid  side  effects  between  tests.
4. Test run:
4.1 An @Before annotated method is executed, if one
exists.
4.2 An @Test-method is executed.
4.3 An @After annotated method is executed, if one exists.
5. This cycle repeats starting from step 3 until all test methods
have been executed.
A Practical Guide - JUnit
Advanced JUnit features
• Predefined  maximum runtime of a test:
@Test(timeout = 1000l)
• Expected exception:
@Test(expected=NullPointerException.class)
• Flow of execution must not come to certain point:
fail("message") makes the test fail anyhow
A Practical Guide - JUnit
Parameterized Tests
Idea: run one test with several parameter sets.
• 1. Annotate your test class with
@RunWith(Parameterized.class).
• 2. Implement a noarg public static method annotated with
@Parameters,returning a Collection of Arrays.
• 3. Each element of the array must contain the expected value
and all required parameters.
• 4. Implement a constructor setting these values to instance
variables of the test.
• 5. Implement one test method using the parameters.
A Practical Guide - JUnit
@RunWith(Parameterized.class)
public class PrimeNumberValidatorTest {
private Integer primeNumber;
private Boolean expectedValidation;
private PrimeNumberValidator primeNumberValidator;
@Before
public void initialize() {
primeNumberValidator = new PrimeNumberValidator();
}

// Each parameter should be placed as an argument here
// Every time runner triggers, it will pass the arguments from parameters we defined
public PrimeNumberValidatorTest(Integer primeNumber, Boolean expectedValidation) {
this.primeNumber = primeNumber;
this.expectedValidation = expectedValidation;
}
@Parameterized.Parameters
public static Collection primeNumbers() {
return Arrays.asList(new Object[][] {
{ 2, true },
{ 6, false },
{ 19, true },
{ 22, false }
});
}

}

// This test will run 4 times since we have 4 parameters defined
@Test
public void testPrimeNumberValidator() {
assertEquals(expectedValidation, primeNumberValidator.validate(primeNumber));
}
A Practical Guide - JUnit
Tips writing Tests
•
•
•
•
•
•
•

•
•
•
•
•

Test the simple stuff first
Use assertEquals as much as possible
Use the message argument
Keep test methods simple
Test boundary conditions early
Keep your tests independent of each other
Use fined-grained interfaces liberally (make it easier to create and
maintain mock implementations)
Avoid System.out and System.err in your tests
Avoid testing against databases and network resources
Add a main() to your test cases (doing this lets easily run any test from
command line or other tool)
Start with the assert (and continue backwards)
Always write a toString() method (failure reports will be more
informative, saving time and effort)
Thank  you  for  your  patience….

More Related Content

What's hot

Google mock for dummies
Google mock for dummiesGoogle mock for dummies
Google mock for dummies
Harry Potter
 
Advanced junit and mockito
Advanced junit and mockitoAdvanced junit and mockito
Advanced junit and mockito
Mathieu Carbou
 

What's hot (19)

Junit
JunitJunit
Junit
 
關於測試,我說的其實是......
關於測試,我說的其實是......關於測試,我說的其實是......
關於測試,我說的其實是......
 
Google mock for dummies
Google mock for dummiesGoogle mock for dummies
Google mock for dummies
 
xUnit Style Database Testing
xUnit Style Database TestingxUnit Style Database Testing
xUnit Style Database Testing
 
Junit, mockito, etc
Junit, mockito, etcJunit, mockito, etc
Junit, mockito, etc
 
Mockito
MockitoMockito
Mockito
 
Unit Testing - The Whys, Whens and Hows
Unit Testing - The Whys, Whens and HowsUnit Testing - The Whys, Whens and Hows
Unit Testing - The Whys, Whens and Hows
 
Advanced junit and mockito
Advanced junit and mockitoAdvanced junit and mockito
Advanced junit and mockito
 
Qunit Java script Un
Qunit Java script UnQunit Java script Un
Qunit Java script Un
 
[Webinar] Qt Test-Driven Development Using Google Test and Google Mock
[Webinar] Qt Test-Driven Development Using Google Test and Google Mock[Webinar] Qt Test-Driven Development Using Google Test and Google Mock
[Webinar] Qt Test-Driven Development Using Google Test and Google Mock
 
TDD Training
TDD TrainingTDD Training
TDD Training
 
Testing with Junit4
Testing with Junit4Testing with Junit4
Testing with Junit4
 
Testing in-python-and-pytest-framework
Testing in-python-and-pytest-frameworkTesting in-python-and-pytest-framework
Testing in-python-and-pytest-framework
 
Junit
JunitJunit
Junit
 
Unit testing with java
Unit testing with javaUnit testing with java
Unit testing with java
 
JAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
JAVASCRIPT TDD(Test driven Development) & Qunit TutorialJAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
JAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
 
Sample Chapter of Practical Unit Testing with TestNG and Mockito
Sample Chapter of Practical Unit Testing with TestNG and MockitoSample Chapter of Practical Unit Testing with TestNG and Mockito
Sample Chapter of Practical Unit Testing with TestNG and Mockito
 
JUnit 5 - The Next Generation of JUnit - Ted's Tool Time
JUnit 5 - The Next Generation of JUnit - Ted's Tool TimeJUnit 5 - The Next Generation of JUnit - Ted's Tool Time
JUnit 5 - The Next Generation of JUnit - Ted's Tool Time
 
Python testing
Python  testingPython  testing
Python testing
 

Similar to Test driven development

J unit presentation
J unit presentationJ unit presentation
J unit presentation
Priya Sharma
 

Similar to Test driven development (20)

Describe's Full of It's
Describe's Full of It'sDescribe's Full of It's
Describe's Full of It's
 
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
 
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
 
Junit 4.0
Junit 4.0Junit 4.0
Junit 4.0
 
31b - JUnit and Mockito.pdf
31b - JUnit and Mockito.pdf31b - JUnit and Mockito.pdf
31b - JUnit and Mockito.pdf
 
Developer Tests - Things to Know (Vilnius JUG)
Developer Tests - Things to Know (Vilnius JUG)Developer Tests - Things to Know (Vilnius JUG)
Developer Tests - Things to Know (Vilnius JUG)
 
Qt test framework
Qt test frameworkQt test framework
Qt test framework
 
J unit presentation
J unit presentationJ unit presentation
J unit presentation
 
JUnit Presentation
JUnit PresentationJUnit Presentation
JUnit Presentation
 
Test Driven Development with JavaFX
Test Driven Development with JavaFXTest Driven Development with JavaFX
Test Driven Development with JavaFX
 
Intro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJSIntro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJS
 
VT.NET 20160411: An Intro to Test Driven Development (TDD)
VT.NET 20160411: An Intro to Test Driven Development (TDD)VT.NET 20160411: An Intro to Test Driven Development (TDD)
VT.NET 20160411: An Intro to Test Driven Development (TDD)
 
Unit testing basics
Unit testing basicsUnit testing basics
Unit testing basics
 
Kill the mutants - A better way to test your tests
Kill the mutants - A better way to test your testsKill the mutants - A better way to test your tests
Kill the mutants - A better way to test your tests
 
Kill the mutants and test your tests - Roy van Rijn
Kill the mutants and test your tests - Roy van RijnKill the mutants and test your tests - Roy van Rijn
Kill the mutants and test your tests - Roy van Rijn
 
Unit tests and TDD
Unit tests and TDDUnit tests and TDD
Unit tests and TDD
 
Testing Spring Applications
Testing Spring ApplicationsTesting Spring Applications
Testing Spring Applications
 
Test Driven Development with Sql Server
Test Driven Development with Sql ServerTest Driven Development with Sql Server
Test Driven Development with Sql Server
 
API Performance Testing
API Performance TestingAPI Performance Testing
API Performance Testing
 
Junit mockito and PowerMock in Java
Junit mockito and  PowerMock in JavaJunit mockito and  PowerMock in Java
Junit mockito and PowerMock in Java
 

Recently uploaded

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Recently uploaded (20)

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
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
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
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
[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
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
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
 
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...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
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
 
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...
 
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
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech 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
 
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
 
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
 
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
 
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
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 

Test driven development

  • 1. Test Driven Development “TDD  is  not  testing,  it  is  a  design  technique”. Christoforos Nalmpantis
  • 2. What is TDD TDD is a style of development where: • You maintain an exhaustive suite of Programmer Tests • No code goes into production unless it has associated tests • You write the tests first • The tests determine what code you need to write
  • 3. Red – Green - Refactor 1. Write a test that fails RED REFACTOR 3. Eliminate redundancy GREEN 2. Make the code work
  • 4. A sad misconception Because of the name of TDD most inexperienced developers believe it is testing. This leads to the following objections: • Writing unit tests takes too much time. • How  could  I  write  tests  first  if  I  don’t  know  what  it  does  yet? • Unit tests won't catch all the bugs.
  • 5. A sad misconception In fact TDD is a design technique and our objections should be: • Designing takes too much time. • How could I design first if I don't know what it does yet? • Designing won't catch all the bugs.
  • 7. TDD is Agile “Agile”  means: • Characterized by quickness, lightness, and ease of movement; nimble. • Mentally quick or alert SCRUM WORKING SOFTWARE ADAPTABILITY extreme programming DAILY TRANSPARENCY UNITY ITERATION continuous CRYSTAL SIMPLICITY RELEASE
  • 9. Why TDD • Ensures quality • Keeps code clear, simple and testable • Provides documentation for different team members • Repeatable tests • Enables rapid change
  • 10. Why TDD “When  you  already  have  Tests that documents how your code works  and  also  verifies  every  logical  units,  programmer’s  bugs   are significantly reduced resulting more time coding, less time debugging.” “You  can  confidently refactor your production code without worrying about breaking it, if you already have test code written, it  acts  as  safety  net.” “Tests  on  TDD  describe  the  behaviour of the code you are going to write. So, tests provides better picture of specification than documentation written on a paper because test runs.”
  • 11. A Practical Guide - Refactoring • • • • • • • • • • • • • • • • • • • • • • • • • • • • public void init() { setLayout(); initMovieList(); initMovieField(); initAddButton(); } private void setLayout() { getContentPane().setLayout(new FlowLayout()); } private void initMovieList() { movieList = new JList(getMovies(); JScrollPane scroller = new JScrollpane(movieList); getContentPane().add(scroller); } private void initMovieField() { movieField = new JTextField(16); getContentPane().add(movieField); } private void initAddButton() { addButton = new JButton(“Add”); addButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { myEditor.add(movie.getText()); movieList.setListData(myEditor.getMovies()); } }); getContentPane().add(addButton); } • • • • • • • • • • • • • • • • Public void init() { getContentPane().setLayout(new FlowLayout()); movieList = new JList(myEditor.getMoviews()); JScrollPane scroller = new JScrollPane(movieList); getContentPane().add(scroller); movieField = new JTextField(16); getContentPane().add(movieField); addButton = new JButton(“Add”); addButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { myEditor.add(movie.getText()); movieList.setListData(myEditor.getMovies()); } }); getContentPane().add(addButton); }
  • 12. A Practical Guide - Refactoring • Extract Method When a method gets too long or the logic is too complex to be easily understood, part of it can be pulled out into a method of its own.
  • 13. A Practical Guide - Refactoring • • • • • • • • • • • • • • • public class Employee { //0-engineer, 1-salesman, 2-manager private String departmentName() { switch (employeeType ) { case 0: return  “Engineering”; case 1: return  “Sales”; case 2: return  “Management”; default: return  “Unknown”; } } } • abstract public class Employee { • Public abstract String departmentName(); • } • public class Engineer extends Employee { • Public String departmentName() { • Return  “Engineering”; • } • } • public class SalesMan extends Employee { • Public String departmentName() { • Return  “Sales”; • } • } • public class Manager extends Employee { • Public String departmentName() { • Return  “Management”; • } • }
  • 14. A Practical Guide - Refactoring • Replace Conditional with Polymorphism When we find switch statements, consider creating subclasses to handle the different cases and get rid of the switch.
  • 15. A Practical Guide - Refactoring • • • • • • • • • • public Money calculateTotal(){ Money subtotal = getSubtotal(); Money tax = getTaxableSubtotal().times(0.15); Money total = subtotal.plus(tax); Boolean qualifiesForDiscount = getSubtotal().asDouble()>100.0; Money discount = qualifiesForDiscount ?subtotal.times(0.10) :new Money(0.0); return total.minus(discount); } • public Money calculateTotal(){ • return getSubtotal().plus((getTaxableSubtotal().times(0.15))) • .minus((getSubtotal().asDouble()>100.0) • ?(getSubtotal().times(0.10)) • :0); • }
  • 16. A Practical Guide - Refactoring • Introduce Explaining Variable When we have a complex expression that is difficult to understand, we can extract parts of it and store the intermediate results in well-named temporary variables. This breaks the expression into easy to understand pieces, as well as making the overall expression clearer.
  • 17. A Practical Guide - Refactoring • public int fib(int i) { • int result; • if(i == 0){ • result = 0; • }else if (i <=2){ • result = 1; • }else { • result = fib( i – 1) + fib(i -2); • } • return result; • } • public int fib( int i ){ • If (i == 0)return 0; • If (i <= 2)return 1; • return fib(i – 1) + fib(i – 2); • }
  • 18. A Practical Guide - Refactoring • Replace Nested Conditional with Guard Clauses Many people have been taught that a method should have only a single exit point. There is no reason for this, certainly not at the expense of clarity. In a method that should exit under multiple conditions, this leads to complex, nested conditional statements. A better, and much clearer alternative is to use guard clauses to return under those conditions.
  • 19. A Practical Guide - Refactoring • • • • • • • Extract class Extract interface Replace Type Code with Subclasses Form Template Method Replace constructor with Factory method Replace Inheritance with Delegation Replace magic number with symbolic constant
  • 20. A Practical Guide - JUnit • JUnit is a Java tool that allows you to easily write tests. • It  uses  Annotations  und  Reflection  (see  one  of  the  next chapters). During execution JUnit runs methods like: @Test public void ...() • JUnit offers  assert-methods to formulate your test outcomes. • Example: assertEquals(5, model.getCurrentValue()); Here, the order is important: expected value, actual value, since an error report says: expected 5 but was ...
  • 21. A Practical Guide - JUnit The Assertions 1. assertEquals(expected, actual) 2. assertEquals(expected, actual, delta) for float  and double obligatory; checks if |expected  −  actual|  <  δ 3. assertNull, assertNotNull 4. assertTrue, assertFalse 5. assertSame, assertNotSame
  • 22. A Practical Guide - JUnit Junit Life Cycle 1. JUnit collects all @Test-Methods in your test class via  Reflection. 2. JUnit executes these methods in isolation from each other, and with undefined  order. 3. JUnit creates a new instance of the test class for each test run in  order  to  avoid  side  effects  between  tests. 4. Test run: 4.1 An @Before annotated method is executed, if one exists. 4.2 An @Test-method is executed. 4.3 An @After annotated method is executed, if one exists. 5. This cycle repeats starting from step 3 until all test methods have been executed.
  • 23. A Practical Guide - JUnit Advanced JUnit features • Predefined  maximum runtime of a test: @Test(timeout = 1000l) • Expected exception: @Test(expected=NullPointerException.class) • Flow of execution must not come to certain point: fail("message") makes the test fail anyhow
  • 24. A Practical Guide - JUnit Parameterized Tests Idea: run one test with several parameter sets. • 1. Annotate your test class with @RunWith(Parameterized.class). • 2. Implement a noarg public static method annotated with @Parameters,returning a Collection of Arrays. • 3. Each element of the array must contain the expected value and all required parameters. • 4. Implement a constructor setting these values to instance variables of the test. • 5. Implement one test method using the parameters.
  • 25. A Practical Guide - JUnit @RunWith(Parameterized.class) public class PrimeNumberValidatorTest { private Integer primeNumber; private Boolean expectedValidation; private PrimeNumberValidator primeNumberValidator; @Before public void initialize() { primeNumberValidator = new PrimeNumberValidator(); } // Each parameter should be placed as an argument here // Every time runner triggers, it will pass the arguments from parameters we defined public PrimeNumberValidatorTest(Integer primeNumber, Boolean expectedValidation) { this.primeNumber = primeNumber; this.expectedValidation = expectedValidation; } @Parameterized.Parameters public static Collection primeNumbers() { return Arrays.asList(new Object[][] { { 2, true }, { 6, false }, { 19, true }, { 22, false } }); } } // This test will run 4 times since we have 4 parameters defined @Test public void testPrimeNumberValidator() { assertEquals(expectedValidation, primeNumberValidator.validate(primeNumber)); }
  • 26. A Practical Guide - JUnit Tips writing Tests • • • • • • • • • • • • Test the simple stuff first Use assertEquals as much as possible Use the message argument Keep test methods simple Test boundary conditions early Keep your tests independent of each other Use fined-grained interfaces liberally (make it easier to create and maintain mock implementations) Avoid System.out and System.err in your tests Avoid testing against databases and network resources Add a main() to your test cases (doing this lets easily run any test from command line or other tool) Start with the assert (and continue backwards) Always write a toString() method (failure reports will be more informative, saving time and effort)
  • 27. Thank  you  for  your  patience….