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 (20)

PDF
Unit testing best practices with JUnit
inTwentyEight Minutes
 
PPTX
Roy Osherove on Unit Testing Good Practices and Horrible Mistakes
Roy Osherove
 
PPTX
Unit testing - the hard parts
Shaun Abram
 
PDF
Clean Unit Test Patterns
Frank Appel
 
PDF
Unit Testing 101
Dave Bouwman
 
PDF
Unit testing best practices
nickokiss
 
PPTX
.Net Unit Testing with Visual Studio 2010
kgayda
 
PDF
Unit Testing Guidelines
Joel Hooks
 
PDF
Unit testing with JUnit
Thomas Zimmermann
 
PPT
Automated Unit Testing
Mike Lively
 
PPTX
Unit testing, UI testing and Test Driven Development in Visual Studio 2012
Jacinto Limjap
 
PDF
Writing good unit test
Lucy Lu
 
PPTX
Tdd & unit test
GomathiNayagam S
 
PDF
Unit Testing
Scott Leberknight
 
PPTX
Unit test
Tran Duc
 
PPTX
Test driven development in .Net - 2010 + Eclipse
UTC Fire & Security
 
PPTX
Java Unit Test and Coverage Introduction
Alex Su
 
PDF
How and what to unit test
Eugenio Lentini
 
PPTX
Unit Tests And Automated Testing
Lee Englestone
 
PPTX
An Introduction to Unit Testing
Joe Tremblay
 
Unit testing best practices with JUnit
inTwentyEight Minutes
 
Roy Osherove on Unit Testing Good Practices and Horrible Mistakes
Roy Osherove
 
Unit testing - the hard parts
Shaun Abram
 
Clean Unit Test Patterns
Frank Appel
 
Unit Testing 101
Dave Bouwman
 
Unit testing best practices
nickokiss
 
.Net Unit Testing with Visual Studio 2010
kgayda
 
Unit Testing Guidelines
Joel Hooks
 
Unit testing with JUnit
Thomas Zimmermann
 
Automated Unit Testing
Mike Lively
 
Unit testing, UI testing and Test Driven Development in Visual Studio 2012
Jacinto Limjap
 
Writing good unit test
Lucy Lu
 
Tdd & unit test
GomathiNayagam S
 
Unit Testing
Scott Leberknight
 
Unit test
Tran Duc
 
Test driven development in .Net - 2010 + Eclipse
UTC Fire & Security
 
Java Unit Test and Coverage Introduction
Alex Su
 
How and what to unit test
Eugenio Lentini
 
Unit Tests And Automated Testing
Lee Englestone
 
An Introduction to Unit Testing
Joe Tremblay
 

Similar to Best practices unit testing (20)

PDF
Developer Test - Things to Know
vilniusjug
 
PPTX
Advance unittest
Reza Arbabi
 
PDF
"Unit Testing for Mobile App" by Fandy Gotama (OLX Indonesia)
Tech in Asia ID
 
PDF
Tech In Asia PDC 2017 - Best practice unit testing in mobile apps
Fandy Gotama
 
PDF
Unit testing basic
Yuri Anischenko
 
PPTX
15 tips to improve your unit tests (Droidcon Berlin 2016 Barcamp)
Danny Preussler
 
PDF
Testing recipes
Jesús Miguel Benito Calzada
 
PDF
How to improve your unit tests?
Péter Módos
 
PDF
33rd Degree 2013, Bad Tests, Good Tests
Tomek Kaczanowski
 
PDF
Developer Tests - Things to Know (Vilnius JUG)
vilniusjug
 
PPTX
Software testing ... who’s responsible is it?
Manjula03809891
 
PPTX
Software testing ... who is responsible for it?
Manjula Piyumal
 
PDF
Developer Tests - Things to Know
Vaidas Pilkauskas
 
PPTX
10 Principles of Apex Testing
Kevin Poorman
 
PDF
Software Testing
AdroitLogic
 
PDF
Art of unit testing: How developer should care about code quality
Dmytro Patserkovskyi
 
PDF
2013 DevFest Vienna - Bad Tests, Good Tests
Tomek Kaczanowski
 
PPTX
Test-Driven Design Insights@DevoxxBE 2023.pptx
Victor Rentea
 
PPTX
Java Unit Test - JUnit
Aktuğ Urun
 
PPTX
The tests are trying to tell you [email protected]
Victor Rentea
 
Developer Test - Things to Know
vilniusjug
 
Advance unittest
Reza Arbabi
 
"Unit Testing for Mobile App" by Fandy Gotama (OLX Indonesia)
Tech in Asia ID
 
Tech In Asia PDC 2017 - Best practice unit testing in mobile apps
Fandy Gotama
 
Unit testing basic
Yuri Anischenko
 
15 tips to improve your unit tests (Droidcon Berlin 2016 Barcamp)
Danny Preussler
 
How to improve your unit tests?
Péter Módos
 
33rd Degree 2013, Bad Tests, Good Tests
Tomek Kaczanowski
 
Developer Tests - Things to Know (Vilnius JUG)
vilniusjug
 
Software testing ... who’s responsible is it?
Manjula03809891
 
Software testing ... who is responsible for it?
Manjula Piyumal
 
Developer Tests - Things to Know
Vaidas Pilkauskas
 
10 Principles of Apex Testing
Kevin Poorman
 
Software Testing
AdroitLogic
 
Art of unit testing: How developer should care about code quality
Dmytro Patserkovskyi
 
2013 DevFest Vienna - Bad Tests, Good Tests
Tomek Kaczanowski
 
Test-Driven Design Insights@DevoxxBE 2023.pptx
Victor Rentea
 
Java Unit Test - JUnit
Aktuğ Urun
 
The tests are trying to tell you [email protected]
Victor Rentea
 
Ad

More from Tricode (part of Dept) (20)

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

Recently uploaded (20)

PPTX
DATA BASE MANAGEMENT AND RELATIONAL DATA
gomathisankariv2
 
PDF
AI TECHNIQUES FOR IDENTIFYING ALTERATIONS IN THE HUMAN GUT MICROBIOME IN MULT...
vidyalalltv1
 
PPTX
Mechanical Design of shell and tube heat exchangers as per ASME Sec VIII Divi...
shahveer210504
 
DOCX
CS-802 (A) BDH Lab manual IPS Academy Indore
thegodhimself05
 
PPTX
Shinkawa Proposal to meet Vibration API670.pptx
AchmadBashori2
 
PPTX
Element 7. CHEMICAL AND BIOLOGICAL AGENT.pptx
merrandomohandas
 
PPTX
Element 11. ELECTRICITY safety and hazards
merrandomohandas
 
PPTX
原版一样(Acadia毕业证书)加拿大阿卡迪亚大学毕业证办理方法
Taqyea
 
PPTX
What is Shot Peening | Shot Peening is a Surface Treatment Process
Vibra Finish
 
PDF
Set Relation Function Practice session 24.05.2025.pdf
DrStephenStrange4
 
PPTX
Depth First Search Algorithm in 🧠 DFS in Artificial Intelligence (AI)
rafeeqshaik212002
 
PPTX
Server Side Web Development Unit 1 of Nodejs.pptx
sneha852132
 
PDF
Electrical Engineer operation Supervisor
ssaruntatapower143
 
PPTX
Worm gear strength and wear calculation as per standard VB Bhandari Databook.
shahveer210504
 
PPTX
artificial intelligence applications in Geomatics
NawrasShatnawi1
 
PPTX
265587293-NFPA 101 Life safety code-PPT-1.pptx
chandermwason
 
PPTX
fatigue in aircraft structures-221113192308-0ad6dc8c.pptx
aviatecofficial
 
PPTX
Green Building & Energy Conservation ppt
Sagar Sarangi
 
PPTX
VITEEE 2026 Exam Details , Important Dates
SonaliSingh127098
 
PDF
Reasons for the succes of MENARD PRESSUREMETER.pdf
majdiamz
 
DATA BASE MANAGEMENT AND RELATIONAL DATA
gomathisankariv2
 
AI TECHNIQUES FOR IDENTIFYING ALTERATIONS IN THE HUMAN GUT MICROBIOME IN MULT...
vidyalalltv1
 
Mechanical Design of shell and tube heat exchangers as per ASME Sec VIII Divi...
shahveer210504
 
CS-802 (A) BDH Lab manual IPS Academy Indore
thegodhimself05
 
Shinkawa Proposal to meet Vibration API670.pptx
AchmadBashori2
 
Element 7. CHEMICAL AND BIOLOGICAL AGENT.pptx
merrandomohandas
 
Element 11. ELECTRICITY safety and hazards
merrandomohandas
 
原版一样(Acadia毕业证书)加拿大阿卡迪亚大学毕业证办理方法
Taqyea
 
What is Shot Peening | Shot Peening is a Surface Treatment Process
Vibra Finish
 
Set Relation Function Practice session 24.05.2025.pdf
DrStephenStrange4
 
Depth First Search Algorithm in 🧠 DFS in Artificial Intelligence (AI)
rafeeqshaik212002
 
Server Side Web Development Unit 1 of Nodejs.pptx
sneha852132
 
Electrical Engineer operation Supervisor
ssaruntatapower143
 
Worm gear strength and wear calculation as per standard VB Bhandari Databook.
shahveer210504
 
artificial intelligence applications in Geomatics
NawrasShatnawi1
 
265587293-NFPA 101 Life safety code-PPT-1.pptx
chandermwason
 
fatigue in aircraft structures-221113192308-0ad6dc8c.pptx
aviatecofficial
 
Green Building & Energy Conservation ppt
Sagar Sarangi
 
VITEEE 2026 Exam Details , Important Dates
SonaliSingh127098
 
Reasons for the succes of MENARD PRESSUREMETER.pdf
majdiamz
 

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 [email protected]
  • 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