SlideShare a Scribd company logo
Unit testing best practices 
Lazo Apostolovski 
Tricode BV 
De Schutterij 12 -18 
3905 PL Veenendaal 
The Netherlands 
tel: 0318 - 559210 
fax: 0318 - 650909 
www.tricode.nl 
info@tricode.nl
Experience is a hard teacher because 
she gives the test first, the lesson 
afterward. 
— Chinese proverb
Don’t make unnecessary assertions 
@Testpublic void scenarioOne() { 
User result = service.doSomething(user); 
assertThat(result.someState(), is(“Yes”)); 
} 
@Testpublic void scenarioTwo() { 
User result = service.doSomething(user); 
assertThat(result.someState(), is(“Yes”)); 
assertThat(result.isEnabled(), is(true)); 
} 
@Testpublic void useless(){ 
assertTrue(false); 
}
Use annotation to test thrown 
exceptions 
GOOD: 
@Test(expected = 
Exception.class)public void 
testSomethig() { 
service.methodThrowsException(); 
} 
BAD: 
@Testpublic void testSomething() { 
boolean haveException = false; 
try { 
service.methodThrowsException(); 
} catch (Exception e) { 
haveException = true; 
} 
assertTrue(haveException); 
}
Don't test Java 
public class MyException extends Exception { 
public MyException(String message) { 
super(message); 
} 
} 
public void someMethod() throws MyException { 
throw new MyException("SomeMessage"); 
} 
@Testpublic void testSomething() { 
try { 
service.someMethod(); 
} catch (MyException e) { 
assertThat(e.getMessage(), is("SomeMessage")); 
} 
}
Don’t test POJO objects 
public class POJO { 
private String field; 
public String getField() { 
return field; 
} 
public void setField(String field) { 
this.field = field; 
} 
} 
@Testpublic void testPojo() { 
POJO pojo = new POJO(); 
pojo.setField("value"); 
assertThat(pojo.getField(), is("value")); 
}
I remember growing up with 
television, from the time it was 
just a test pattern, with maybe a 
little bit of programming once in a 
while. 
— Francis Ford Coppola
Mock all external services 
and states 
@Testpublic void multiple() { 
Dao dao = mock(Dao.class); 
EmailService emailService = mock(EmailService.class); 
RemoteControl remoteControl = mock(RemoteControl.class); 
Service service = new Service(dao, emailService, remoteControl); 
User user = new User(); 
doReturn(10).when(emailService).sendEmail(); 
doReturn(10).when(dao).store(user); 
service.save(user); 
verify(remoteControl, times(1)).turnOn(); 
}
Avoid unnecessary 
preconditions and 
verifications 
public class Service { 
private Dao dao; 
public Service(Dao dao) { 
this.dao = dao; 
} 
public int save(User user) { 
return dao.store(user); 
} 
} 
public interface Dao { 
public int store(Object o); 
public Object read() ; 
} 
@Testpublic void multiple() { 
Dao dao = mock(Dao.class); 
User user = new User(); 
Service service = new Service(dao); 
doReturn(new User()).when(dao).read(); 
doReturn(10).when(dao).store(user); 
assertThat(service.save(user), is(10)); 
verify(dao, times(1)).store(user); 
}
Test one code unit on a time 
public class Service { 
@Testpublic void multiple() { 
Service service = new Service(); 
assertThat(service.doSomething(), is("something")); 
assertThat(service.calculate(), is(10)); 
} 
public String doSomething() { 
return "something"; 
} 
public Integer calculate() { 
return 10; 
} 
}
Write multiple test scenarios 
public class Service { 
public String doSomething() { return "something"; } 
public Integer calculate() { return 10; } 
} 
@Testpublic void testDoSomething() { 
Service service = new Service(); 
assertThat(service.doSomething(), is("something")); 
} 
@Testpublic void testCalculate() { 
Service service = new Service(); 
assertThat(service.calculate(), is(10)); 
}
Don’t rely on indirect testing 
public class Service { 
public String doSomething() { 
return new AnotherService().doSomething(); 
} 
}public class AnotherService { 
public String doSomething() { 
return "someThing"; 
} 
} 
@Testpublic void testAnotherService() { 
Service service = new Service(); 
assertThat(service.doSomething(), is("someThing")); 
}
Design is not just what it looks like 
and feels like. Design is how it 
works. 
— Steve Jobs
If test get complicated, we 
need better code design 
How to indicate bad code design? 
• Complex test objects need to be created to test 
simple scenario (otherwise null pointers are fired) 
• More than 4 dependencies need to be mocked. 
• Test have too much mock statements for one test 
scenario 
• Test is getting more than ~5-10 lines of code. 
• If you get in any of this states,re-factor your code
Give tests good names 
● shouldCreateNewUserForGivenUsername 
● shouldThrowExceptionWhenUsernameIsNull 
● shouldStoreUserToDatabase 
● shouldActivateUserByUsername 
● shouldEncryptUserPassword 
● shouldValidateUserPassword
Don’t skip unit tests 
@Ignore 
@Testpublic void testPojo() { 
Service service = new Service(); 
assertThat(service.doSomething(), is("someThing")); 
} 
● Having invalid test cases in our 
source code will not help anyone. 
● If test scenario is invalid, then 
remove it.
Add new tests for every bug 
you find 
How will this help us? 
• Will keep an eye on a bug for us 
• Will prevent us of making changes that will make 
the bug reappear 
• It is the agile way 
• It always good to have more unit tests
Parametrize where you can 
@RunWith(value = Parameterized.class)public class Example { 
private final Service service = new Service(); 
private final String value; 
private final boolean result; 
@Parameterized.Parameters 
public static Collection<Object[]> data() { 
final Object[][] data = new Object[][]{ {StringUtils.EMPTY, Boolean.FALSE}, 
{"123_some", Boolean.FALSE}, 
{null, Boolean.TRUE}, }; 
return Arrays.asList(data); 
} 
public Example(final String value, final boolean result) { this.value = value; this.result = 
result; } 
@Test 
public void isValid() { 
assertThat(service.doSomething(value), is(equalTo(result))); 
} 
}
Final notes 
Tests are documentation tool. New developer 
can have more insight about what code do. 
Test everything that could possibly break 
Don’t test configuration settings 
Don’t test logging 
Keep tests independent
Follow us: 
tricode.nl 
facebook.com/tricode 
linkedin.com/company/tricode 
slideshare.net/tricode 
twitter.com/tricode

More Related Content

What's hot

Unit testing best practices with JUnit
Unit testing best practices with JUnitUnit testing best practices with JUnit
Unit testing best practices with JUnit
inTwentyEight Minutes
 
Roy Osherove on Unit Testing Good Practices and Horrible Mistakes
Roy Osherove on Unit Testing Good Practices and Horrible MistakesRoy Osherove on Unit Testing Good Practices and Horrible Mistakes
Roy Osherove on Unit Testing Good Practices and Horrible MistakesRoy Osherove
 
Unit testing - the hard parts
Unit testing - the hard partsUnit testing - the hard parts
Unit testing - the hard parts
Shaun Abram
 
Clean Unit Test Patterns
Clean Unit Test PatternsClean Unit Test Patterns
Clean Unit Test Patterns
Frank Appel
 
Unit Testing 101
Unit Testing 101Unit Testing 101
Unit Testing 101
Dave Bouwman
 
Unit testing best practices
Unit testing best practicesUnit testing best practices
Unit testing best practicesnickokiss
 
.Net Unit Testing with Visual Studio 2010
.Net Unit Testing with Visual Studio 2010.Net Unit Testing with Visual Studio 2010
.Net Unit Testing with Visual Studio 2010
kgayda
 
Unit Testing Guidelines
Unit Testing GuidelinesUnit Testing Guidelines
Unit Testing GuidelinesJoel Hooks
 
Unit testing with JUnit
Unit testing with JUnitUnit testing with JUnit
Unit testing with JUnit
Thomas Zimmermann
 
Automated Unit Testing
Automated Unit TestingAutomated Unit Testing
Automated Unit Testing
Mike Lively
 
Unit testing, UI testing and Test Driven Development in Visual Studio 2012
Unit testing, UI testing and Test Driven Development in Visual Studio 2012Unit testing, UI testing and Test Driven Development in Visual Studio 2012
Unit testing, UI testing and Test Driven Development in Visual Studio 2012Jacinto Limjap
 
Writing good unit test
Writing good unit testWriting good unit test
Writing good unit test
Lucy Lu
 
Tdd & unit test
Tdd & unit testTdd & unit test
Tdd & unit test
GomathiNayagam S
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
Scott Leberknight
 
Unit test
Unit testUnit test
Unit test
Tran Duc
 
Test driven development in .Net - 2010 + Eclipse
Test driven development in .Net - 2010 + EclipseTest driven development in .Net - 2010 + Eclipse
Test driven development in .Net - 2010 + Eclipse
UTC Fire & Security
 
Java Unit Test and Coverage Introduction
Java Unit Test and Coverage IntroductionJava Unit Test and Coverage Introduction
Java Unit Test and Coverage IntroductionAlex Su
 
How and what to unit test
How and what to unit testHow and what to unit test
How and what to unit test
Eugenio Lentini
 
Unit Tests And Automated Testing
Unit Tests And Automated TestingUnit Tests And Automated Testing
Unit Tests And Automated Testing
Lee Englestone
 
An Introduction to Unit Testing
An Introduction to Unit TestingAn Introduction to Unit Testing
An Introduction to Unit Testing
Joe Tremblay
 

What's hot (20)

Unit testing best practices with JUnit
Unit testing best practices with JUnitUnit testing best practices with JUnit
Unit testing best practices with JUnit
 
Roy Osherove on Unit Testing Good Practices and Horrible Mistakes
Roy Osherove on Unit Testing Good Practices and Horrible MistakesRoy Osherove on Unit Testing Good Practices and Horrible Mistakes
Roy Osherove on Unit Testing Good Practices and Horrible Mistakes
 
Unit testing - the hard parts
Unit testing - the hard partsUnit testing - the hard parts
Unit testing - the hard parts
 
Clean Unit Test Patterns
Clean Unit Test PatternsClean Unit Test Patterns
Clean Unit Test Patterns
 
Unit Testing 101
Unit Testing 101Unit Testing 101
Unit Testing 101
 
Unit testing best practices
Unit testing best practicesUnit testing best practices
Unit testing best practices
 
.Net Unit Testing with Visual Studio 2010
.Net Unit Testing with Visual Studio 2010.Net Unit Testing with Visual Studio 2010
.Net Unit Testing with Visual Studio 2010
 
Unit Testing Guidelines
Unit Testing GuidelinesUnit Testing Guidelines
Unit Testing Guidelines
 
Unit testing with JUnit
Unit testing with JUnitUnit testing with JUnit
Unit testing with JUnit
 
Automated Unit Testing
Automated Unit TestingAutomated Unit Testing
Automated Unit Testing
 
Unit testing, UI testing and Test Driven Development in Visual Studio 2012
Unit testing, UI testing and Test Driven Development in Visual Studio 2012Unit testing, UI testing and Test Driven Development in Visual Studio 2012
Unit testing, UI testing and Test Driven Development in Visual Studio 2012
 
Writing good unit test
Writing good unit testWriting good unit test
Writing good unit test
 
Tdd & unit test
Tdd & unit testTdd & unit test
Tdd & unit test
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
Unit test
Unit testUnit test
Unit test
 
Test driven development in .Net - 2010 + Eclipse
Test driven development in .Net - 2010 + EclipseTest driven development in .Net - 2010 + Eclipse
Test driven development in .Net - 2010 + Eclipse
 
Java Unit Test and Coverage Introduction
Java Unit Test and Coverage IntroductionJava Unit Test and Coverage Introduction
Java Unit Test and Coverage Introduction
 
How and what to unit test
How and what to unit testHow and what to unit test
How and what to unit test
 
Unit Tests And Automated Testing
Unit Tests And Automated TestingUnit Tests And Automated Testing
Unit Tests And Automated Testing
 
An Introduction to Unit Testing
An Introduction to Unit TestingAn Introduction to Unit Testing
An Introduction to Unit Testing
 

Similar to Best practices unit testing

2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests
Tomek Kaczanowski
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good TestsTomek Kaczanowski
 
How to write clean tests
How to write clean testsHow to write clean tests
How to write clean tests
Danylenko Max
 
How to Start Test-Driven Development in Legacy Code
How to Start Test-Driven Development in Legacy CodeHow to Start Test-Driven Development in Legacy Code
How to Start Test-Driven Development in Legacy Code
Daniel Wellman
 
Confitura 2012 Bad Tests, Good Tests
Confitura 2012 Bad Tests, Good TestsConfitura 2012 Bad Tests, Good Tests
Confitura 2012 Bad Tests, Good Tests
Tomek Kaczanowski
 
GeeCON 2012 Bad Tests, Good Tests
GeeCON 2012 Bad Tests, Good TestsGeeCON 2012 Bad Tests, Good Tests
GeeCON 2012 Bad Tests, Good Tests
Tomek Kaczanowski
 
Developer Test - Things to Know
Developer Test - Things to KnowDeveloper Test - Things to Know
Developer Test - Things to Know
vilniusjug
 
Mutation Testing
Mutation TestingMutation Testing
Mutation Testing
Chris Sinjakli
 
Mutation Testing: Start Hunting The Bugs
Mutation Testing: Start Hunting The BugsMutation Testing: Start Hunting The Bugs
Mutation Testing: Start Hunting The Bugs
Ari Waller
 
Iterative architecture
Iterative architectureIterative architecture
Iterative architecture
JoshuaRizzo4
 
1 aleksandr gritsevski - attd example using
1   aleksandr gritsevski - attd example using1   aleksandr gritsevski - attd example using
1 aleksandr gritsevski - attd example using
Ievgenii Katsan
 
STAMP Descartes Presentation
STAMP Descartes PresentationSTAMP Descartes Presentation
STAMP Descartes Presentation
STAMP Project
 
Understanding JavaScript Testing
Understanding JavaScript TestingUnderstanding JavaScript Testing
Understanding JavaScript Testing
jeresig
 
Testing, Performance Analysis, and jQuery 1.4
Testing, Performance Analysis, and jQuery 1.4Testing, Performance Analysis, and jQuery 1.4
Testing, Performance Analysis, and jQuery 1.4
jeresig
 
Working effectively with legacy code
Working effectively with legacy codeWorking effectively with legacy code
Working effectively with legacy codeShriKant Vashishtha
 
Unit Testing Front End JavaScript
Unit Testing Front End JavaScriptUnit Testing Front End JavaScript
Unit Testing Front End JavaScript
FITC
 
Test driven development
Test driven developmentTest driven development
Test driven development
christoforosnalmpantis
 
Unit testing patterns for concurrent code
Unit testing patterns for concurrent codeUnit testing patterns for concurrent code
Unit testing patterns for concurrent code
Dror Helper
 
Mutation @ Spotify
Mutation @ Spotify Mutation @ Spotify
Mutation @ Spotify
STAMP Project
 
Advance unittest
Advance unittestAdvance unittest
Advance unittestReza Arbabi
 

Similar to Best practices unit testing (20)

2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests
 
How to write clean tests
How to write clean testsHow to write clean tests
How to write clean tests
 
How to Start Test-Driven Development in Legacy Code
How to Start Test-Driven Development in Legacy CodeHow to Start Test-Driven Development in Legacy Code
How to Start Test-Driven Development in Legacy Code
 
Confitura 2012 Bad Tests, Good Tests
Confitura 2012 Bad Tests, Good TestsConfitura 2012 Bad Tests, Good Tests
Confitura 2012 Bad Tests, Good Tests
 
GeeCON 2012 Bad Tests, Good Tests
GeeCON 2012 Bad Tests, Good TestsGeeCON 2012 Bad Tests, Good Tests
GeeCON 2012 Bad Tests, Good Tests
 
Developer Test - Things to Know
Developer Test - Things to KnowDeveloper Test - Things to Know
Developer Test - Things to Know
 
Mutation Testing
Mutation TestingMutation Testing
Mutation Testing
 
Mutation Testing: Start Hunting The Bugs
Mutation Testing: Start Hunting The BugsMutation Testing: Start Hunting The Bugs
Mutation Testing: Start Hunting The Bugs
 
Iterative architecture
Iterative architectureIterative architecture
Iterative architecture
 
1 aleksandr gritsevski - attd example using
1   aleksandr gritsevski - attd example using1   aleksandr gritsevski - attd example using
1 aleksandr gritsevski - attd example using
 
STAMP Descartes Presentation
STAMP Descartes PresentationSTAMP Descartes Presentation
STAMP Descartes Presentation
 
Understanding JavaScript Testing
Understanding JavaScript TestingUnderstanding JavaScript Testing
Understanding JavaScript Testing
 
Testing, Performance Analysis, and jQuery 1.4
Testing, Performance Analysis, and jQuery 1.4Testing, Performance Analysis, and jQuery 1.4
Testing, Performance Analysis, and jQuery 1.4
 
Working effectively with legacy code
Working effectively with legacy codeWorking effectively with legacy code
Working effectively with legacy code
 
Unit Testing Front End JavaScript
Unit Testing Front End JavaScriptUnit Testing Front End JavaScript
Unit Testing Front End JavaScript
 
Test driven development
Test driven developmentTest driven development
Test driven development
 
Unit testing patterns for concurrent code
Unit testing patterns for concurrent codeUnit testing patterns for concurrent code
Unit testing patterns for concurrent code
 
Mutation @ Spotify
Mutation @ Spotify Mutation @ Spotify
Mutation @ Spotify
 
Advance unittest
Advance unittestAdvance unittest
Advance unittest
 

More from Tricode (part of Dept)

The Top Benefits of Magnolia CMS’s Inspirational Open Suite Ideology
The Top Benefits of Magnolia CMS’s Inspirational Open Suite IdeologyThe Top Benefits of Magnolia CMS’s Inspirational Open Suite Ideology
The Top Benefits of Magnolia CMS’s Inspirational Open Suite Ideology
Tricode (part of Dept)
 
Agile QA 2017: A New Hope
Agile QA 2017: A New HopeAgile QA 2017: A New Hope
Agile QA 2017: A New Hope
Tricode (part of Dept)
 
Mobile Sensor Networks based on Smartphone devices and Web Services
Mobile Sensor Networks based on Smartphone devices and Web ServicesMobile Sensor Networks based on Smartphone devices and Web Services
Mobile Sensor Networks based on Smartphone devices and Web Services
Tricode (part of Dept)
 
Keeping Your Clients Happy and Your Management Even Happier
Keeping Your Clients Happy and Your Management Even Happier Keeping Your Clients Happy and Your Management Even Happier
Keeping Your Clients Happy and Your Management Even Happier
Tricode (part of Dept)
 
Intro to JHipster
Intro to JHipster Intro to JHipster
Intro to JHipster
Tricode (part of Dept)
 
Porn, the leading influencer of Technology
Porn, the leading influencer of Technology Porn, the leading influencer of Technology
Porn, the leading influencer of Technology
Tricode (part of Dept)
 
De 4 belangrijkste risicofactoren van het nearshoring proces
De 4 belangrijkste risicofactoren van het nearshoring procesDe 4 belangrijkste risicofactoren van het nearshoring proces
De 4 belangrijkste risicofactoren van het nearshoring proces
Tricode (part of Dept)
 
Internet Addiction (Social Media Edition)
Internet Addiction (Social Media Edition)Internet Addiction (Social Media Edition)
Internet Addiction (Social Media Edition)
Tricode (part of Dept)
 
Kids Can Code - an interactive IT workshop
Kids Can Code - an interactive IT workshopKids Can Code - an interactive IT workshop
Kids Can Code - an interactive IT workshop
Tricode (part of Dept)
 
RESTful API - Best Practices
RESTful API - Best PracticesRESTful API - Best Practices
RESTful API - Best Practices
Tricode (part of Dept)
 
Deep Learning - STM 6
Deep Learning - STM 6Deep Learning - STM 6
Deep Learning - STM 6
Tricode (part of Dept)
 
How Technology is Affecting Society - STM 6
How Technology is Affecting Society - STM 6How Technology is Affecting Society - STM 6
How Technology is Affecting Society - STM 6
Tricode (part of Dept)
 
Monolithic to Microservices Architecture - STM 6
Monolithic to Microservices Architecture - STM 6Monolithic to Microservices Architecture - STM 6
Monolithic to Microservices Architecture - STM 6
Tricode (part of Dept)
 
Customers speak on Magnolia CMS
Customers speak on Magnolia CMSCustomers speak on Magnolia CMS
Customers speak on Magnolia CMS
Tricode (part of Dept)
 
Quality Nearshoring met Tricode
Quality Nearshoring met TricodeQuality Nearshoring met Tricode
Quality Nearshoring met Tricode
Tricode (part of Dept)
 
AEM Digital Assets Management - What's new in 6.2?
AEM Digital Assets Management - What's new in 6.2?AEM Digital Assets Management - What's new in 6.2?
AEM Digital Assets Management - What's new in 6.2?
Tricode (part of Dept)
 
10 nearshoring it trends om in 2016 te volgen
10 nearshoring it trends om in 2016 te volgen 10 nearshoring it trends om in 2016 te volgen
10 nearshoring it trends om in 2016 te volgen
Tricode (part of Dept)
 
Tricode & Magnolia
Tricode & MagnoliaTricode & Magnolia
Tricode & Magnolia
Tricode (part of Dept)
 
Why you should use Adobe Experience Manager Mobile
Why you should use Adobe Experience Manager Mobile Why you should use Adobe Experience Manager Mobile
Why you should use Adobe Experience Manager Mobile
Tricode (part of Dept)
 
Introducing: Tricode's Software Factory
Introducing: Tricode's Software FactoryIntroducing: Tricode's Software Factory
Introducing: Tricode's Software Factory
Tricode (part of Dept)
 

More from Tricode (part of Dept) (20)

The Top Benefits of Magnolia CMS’s Inspirational Open Suite Ideology
The Top Benefits of Magnolia CMS’s Inspirational Open Suite IdeologyThe Top Benefits of Magnolia CMS’s Inspirational Open Suite Ideology
The Top Benefits of Magnolia CMS’s Inspirational Open Suite Ideology
 
Agile QA 2017: A New Hope
Agile QA 2017: A New HopeAgile QA 2017: A New Hope
Agile QA 2017: A New Hope
 
Mobile Sensor Networks based on Smartphone devices and Web Services
Mobile Sensor Networks based on Smartphone devices and Web ServicesMobile Sensor Networks based on Smartphone devices and Web Services
Mobile Sensor Networks based on Smartphone devices and Web Services
 
Keeping Your Clients Happy and Your Management Even Happier
Keeping Your Clients Happy and Your Management Even Happier Keeping Your Clients Happy and Your Management Even Happier
Keeping Your Clients Happy and Your Management Even Happier
 
Intro to JHipster
Intro to JHipster Intro to JHipster
Intro to JHipster
 
Porn, the leading influencer of Technology
Porn, the leading influencer of Technology Porn, the leading influencer of Technology
Porn, the leading influencer of Technology
 
De 4 belangrijkste risicofactoren van het nearshoring proces
De 4 belangrijkste risicofactoren van het nearshoring procesDe 4 belangrijkste risicofactoren van het nearshoring proces
De 4 belangrijkste risicofactoren van het nearshoring proces
 
Internet Addiction (Social Media Edition)
Internet Addiction (Social Media Edition)Internet Addiction (Social Media Edition)
Internet Addiction (Social Media Edition)
 
Kids Can Code - an interactive IT workshop
Kids Can Code - an interactive IT workshopKids Can Code - an interactive IT workshop
Kids Can Code - an interactive IT workshop
 
RESTful API - Best Practices
RESTful API - Best PracticesRESTful API - Best Practices
RESTful API - Best Practices
 
Deep Learning - STM 6
Deep Learning - STM 6Deep Learning - STM 6
Deep Learning - STM 6
 
How Technology is Affecting Society - STM 6
How Technology is Affecting Society - STM 6How Technology is Affecting Society - STM 6
How Technology is Affecting Society - STM 6
 
Monolithic to Microservices Architecture - STM 6
Monolithic to Microservices Architecture - STM 6Monolithic to Microservices Architecture - STM 6
Monolithic to Microservices Architecture - STM 6
 
Customers speak on Magnolia CMS
Customers speak on Magnolia CMSCustomers speak on Magnolia CMS
Customers speak on Magnolia CMS
 
Quality Nearshoring met Tricode
Quality Nearshoring met TricodeQuality Nearshoring met Tricode
Quality Nearshoring met Tricode
 
AEM Digital Assets Management - What's new in 6.2?
AEM Digital Assets Management - What's new in 6.2?AEM Digital Assets Management - What's new in 6.2?
AEM Digital Assets Management - What's new in 6.2?
 
10 nearshoring it trends om in 2016 te volgen
10 nearshoring it trends om in 2016 te volgen 10 nearshoring it trends om in 2016 te volgen
10 nearshoring it trends om in 2016 te volgen
 
Tricode & Magnolia
Tricode & MagnoliaTricode & Magnolia
Tricode & Magnolia
 
Why you should use Adobe Experience Manager Mobile
Why you should use Adobe Experience Manager Mobile Why you should use Adobe Experience Manager Mobile
Why you should use Adobe Experience Manager Mobile
 
Introducing: Tricode's Software Factory
Introducing: Tricode's Software FactoryIntroducing: Tricode's Software Factory
Introducing: Tricode's Software Factory
 

Recently uploaded

power quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptxpower quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptx
ViniHema
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
obonagu
 
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
H.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdfH.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdf
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
MLILAB
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
MdTanvirMahtab2
 
addressing modes in computer architecture
addressing modes  in computer architectureaddressing modes  in computer architecture
addressing modes in computer architecture
ShahidSultan24
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
fxintegritypublishin
 
block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
Divya Somashekar
 
Quality defects in TMT Bars, Possible causes and Potential Solutions.
Quality defects in TMT Bars, Possible causes and Potential Solutions.Quality defects in TMT Bars, Possible causes and Potential Solutions.
Quality defects in TMT Bars, Possible causes and Potential Solutions.
PrashantGoswami42
 
ethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.pptethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.ppt
Jayaprasanna4
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Teleport Manpower Consultant
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
VENKATESHvenky89705
 
Event Management System Vb Net Project Report.pdf
Event Management System Vb Net  Project Report.pdfEvent Management System Vb Net  Project Report.pdf
Event Management System Vb Net Project Report.pdf
Kamal Acharya
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
gdsczhcet
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
Amil Baba Dawood bangali
 
WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234
AafreenAbuthahir2
 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
Robbie Edward Sayers
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation & Control
 
Forklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella PartsForklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella Parts
Intella Parts
 
TECHNICAL TRAINING MANUAL GENERAL FAMILIARIZATION COURSE
TECHNICAL TRAINING MANUAL   GENERAL FAMILIARIZATION COURSETECHNICAL TRAINING MANUAL   GENERAL FAMILIARIZATION COURSE
TECHNICAL TRAINING MANUAL GENERAL FAMILIARIZATION COURSE
DuvanRamosGarzon1
 
Courier management system project report.pdf
Courier management system project report.pdfCourier management system project report.pdf
Courier management system project report.pdf
Kamal Acharya
 

Recently uploaded (20)

power quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptxpower quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptx
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
 
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
H.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdfH.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdf
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
 
addressing modes in computer architecture
addressing modes  in computer architectureaddressing modes  in computer architecture
addressing modes in computer architecture
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
 
block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
 
Quality defects in TMT Bars, Possible causes and Potential Solutions.
Quality defects in TMT Bars, Possible causes and Potential Solutions.Quality defects in TMT Bars, Possible causes and Potential Solutions.
Quality defects in TMT Bars, Possible causes and Potential Solutions.
 
ethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.pptethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.ppt
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
 
Event Management System Vb Net Project Report.pdf
Event Management System Vb Net  Project Report.pdfEvent Management System Vb Net  Project Report.pdf
Event Management System Vb Net Project Report.pdf
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
 
WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234
 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
 
Forklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella PartsForklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella Parts
 
TECHNICAL TRAINING MANUAL GENERAL FAMILIARIZATION COURSE
TECHNICAL TRAINING MANUAL   GENERAL FAMILIARIZATION COURSETECHNICAL TRAINING MANUAL   GENERAL FAMILIARIZATION COURSE
TECHNICAL TRAINING MANUAL GENERAL FAMILIARIZATION COURSE
 
Courier management system project report.pdf
Courier management system project report.pdfCourier management system project report.pdf
Courier management system project report.pdf
 

Best practices unit testing

  • 1. Unit testing best practices Lazo Apostolovski Tricode BV De Schutterij 12 -18 3905 PL Veenendaal The Netherlands tel: 0318 - 559210 fax: 0318 - 650909 www.tricode.nl info@tricode.nl
  • 2. Experience is a hard teacher because she gives the test first, the lesson afterward. — Chinese proverb
  • 3. Don’t make unnecessary assertions @Testpublic void scenarioOne() { User result = service.doSomething(user); assertThat(result.someState(), is(“Yes”)); } @Testpublic void scenarioTwo() { User result = service.doSomething(user); assertThat(result.someState(), is(“Yes”)); assertThat(result.isEnabled(), is(true)); } @Testpublic void useless(){ assertTrue(false); }
  • 4. Use annotation to test thrown exceptions GOOD: @Test(expected = Exception.class)public void testSomethig() { service.methodThrowsException(); } BAD: @Testpublic void testSomething() { boolean haveException = false; try { service.methodThrowsException(); } catch (Exception e) { haveException = true; } assertTrue(haveException); }
  • 5. Don't test Java public class MyException extends Exception { public MyException(String message) { super(message); } } public void someMethod() throws MyException { throw new MyException("SomeMessage"); } @Testpublic void testSomething() { try { service.someMethod(); } catch (MyException e) { assertThat(e.getMessage(), is("SomeMessage")); } }
  • 6. Don’t test POJO objects public class POJO { private String field; public String getField() { return field; } public void setField(String field) { this.field = field; } } @Testpublic void testPojo() { POJO pojo = new POJO(); pojo.setField("value"); assertThat(pojo.getField(), is("value")); }
  • 7. I remember growing up with television, from the time it was just a test pattern, with maybe a little bit of programming once in a while. — Francis Ford Coppola
  • 8. Mock all external services and states @Testpublic void multiple() { Dao dao = mock(Dao.class); EmailService emailService = mock(EmailService.class); RemoteControl remoteControl = mock(RemoteControl.class); Service service = new Service(dao, emailService, remoteControl); User user = new User(); doReturn(10).when(emailService).sendEmail(); doReturn(10).when(dao).store(user); service.save(user); verify(remoteControl, times(1)).turnOn(); }
  • 9. Avoid unnecessary preconditions and verifications public class Service { private Dao dao; public Service(Dao dao) { this.dao = dao; } public int save(User user) { return dao.store(user); } } public interface Dao { public int store(Object o); public Object read() ; } @Testpublic void multiple() { Dao dao = mock(Dao.class); User user = new User(); Service service = new Service(dao); doReturn(new User()).when(dao).read(); doReturn(10).when(dao).store(user); assertThat(service.save(user), is(10)); verify(dao, times(1)).store(user); }
  • 10. Test one code unit on a time public class Service { @Testpublic void multiple() { Service service = new Service(); assertThat(service.doSomething(), is("something")); assertThat(service.calculate(), is(10)); } public String doSomething() { return "something"; } public Integer calculate() { return 10; } }
  • 11. Write multiple test scenarios public class Service { public String doSomething() { return "something"; } public Integer calculate() { return 10; } } @Testpublic void testDoSomething() { Service service = new Service(); assertThat(service.doSomething(), is("something")); } @Testpublic void testCalculate() { Service service = new Service(); assertThat(service.calculate(), is(10)); }
  • 12. Don’t rely on indirect testing public class Service { public String doSomething() { return new AnotherService().doSomething(); } }public class AnotherService { public String doSomething() { return "someThing"; } } @Testpublic void testAnotherService() { Service service = new Service(); assertThat(service.doSomething(), is("someThing")); }
  • 13. Design is not just what it looks like and feels like. Design is how it works. — Steve Jobs
  • 14. If test get complicated, we need better code design How to indicate bad code design? • Complex test objects need to be created to test simple scenario (otherwise null pointers are fired) • More than 4 dependencies need to be mocked. • Test have too much mock statements for one test scenario • Test is getting more than ~5-10 lines of code. • If you get in any of this states,re-factor your code
  • 15. Give tests good names ● shouldCreateNewUserForGivenUsername ● shouldThrowExceptionWhenUsernameIsNull ● shouldStoreUserToDatabase ● shouldActivateUserByUsername ● shouldEncryptUserPassword ● shouldValidateUserPassword
  • 16. Don’t skip unit tests @Ignore @Testpublic void testPojo() { Service service = new Service(); assertThat(service.doSomething(), is("someThing")); } ● Having invalid test cases in our source code will not help anyone. ● If test scenario is invalid, then remove it.
  • 17. Add new tests for every bug you find How will this help us? • Will keep an eye on a bug for us • Will prevent us of making changes that will make the bug reappear • It is the agile way • It always good to have more unit tests
  • 18. Parametrize where you can @RunWith(value = Parameterized.class)public class Example { private final Service service = new Service(); private final String value; private final boolean result; @Parameterized.Parameters public static Collection<Object[]> data() { final Object[][] data = new Object[][]{ {StringUtils.EMPTY, Boolean.FALSE}, {"123_some", Boolean.FALSE}, {null, Boolean.TRUE}, }; return Arrays.asList(data); } public Example(final String value, final boolean result) { this.value = value; this.result = result; } @Test public void isValid() { assertThat(service.doSomething(value), is(equalTo(result))); } }
  • 19. Final notes Tests are documentation tool. New developer can have more insight about what code do. Test everything that could possibly break Don’t test configuration settings Don’t test logging Keep tests independent
  • 20. Follow us: tricode.nl facebook.com/tricode linkedin.com/company/tricode slideshare.net/tricode twitter.com/tricode