SlideShare uma empresa Scribd logo
1 de 38
Automatic test anti-patterns

Ing. Jiří Kiml,
20/11/2013, ZCU

www.querity.cz
Agenda
►Motivation
►What is automatic test
►Anti-patterns catalog
►Basic mistakes
►Best practices
►Summary
►Questions

www.querity.cz
Motivation
Any fool can write code that a computer can understand.
Good programmers write code that humans can understand.
~Martin Fowler

►Detect REAL bugs early
►Avoid boring regression tests
►Better design, api documentation
►Code quality
www.querity.cz
www.querity.cz
Agenda
►Motivation
►What is automatic test
►Anti-patterns catalog
►Basic mistakes
►Best practices
►Summary
►Questions

www.querity.cz
What is automatic test
►No definition in wiki ;-(
►….. example in eclipse

www.querity.cz
Agenda
►Motivation
►What is automatic test
►Anti-patterns catalog
►Basic mistakes
►Best practices
►Summary
►Questions

www.querity.cz
Anti-patterns catalog
The Liar, Excessive Setup, The Giant,
The Mockery, The Inspector, Generous
Leftovers, The Local Hero, The Nitpicker,
The Secret Catcher, The Dodger,
The Loudmouth, The Greedy Catcher
The Sequencer, Hidden Dependency
The Enumerator, The Stranger,
The Operating System Evangelist,
Success Against All Odds, The Free Ride
The One, The Peeping Tom
The Slow Poke
www.querity.cz
Anti-patterns catalog (2)
http://blog.jamescarr.org/2006/11/03/tdd-anti-patterns/
http://stackoverflow.com/questions/333
682/tdd-anti-patterns-catalogue

www.querity.cz
Agenda
►Motivation
►What is automatic test
►Anti-patterns catalog
►Basic mistakes
►Best practices
►Summary
►Questions

www.querity.cz
Basic mistakes
►No tests
►Manual (missing) Assertions
►Redundant Assertions
►Using the Wrong Assert
►Only Easy/Happy Path Tests
►Complex Tests
►External Dependencies
►Catching Unexpected Exceptions
►Mixing Production and Test Code
www.querity.cz
No tests
►Still common in many companies
►“It is to expensive to write tests.”
►“We will write tests later”. (never)
►The Liar, Success Against All Odds

www.querity.cz
No tests
// TODO: This tests need to be activated when nightly db-reset is done!
@Ignore
@Test
public void testXXX() {
...
}
@Test
public void testYYY() {
// TODO implement me
}

www.querity.cz
Manual (missing) Assertions
►Sysout instead of assert
►Why not just use a debugger?
►The Secret Catcher
"Debugging is twice as hard as writing the code
in the first place.
Therefore, if you write the code as cleverly as possible,
you are, by definition, not smart enough to debug it."
Brian W. Kernighan
www.querity.cz
Manual (missing) Assertions
public void testCalculation() {
deepThought.calculate();
System.out.println(deepThought.getResult());
}

public void testCalculation() {
deepThought.calculate();
assertEquals(42, deepThought.getResult());
}

www.querity.cz
Redundant Assertions
►Always true or always false assertions
►Introduced by mistake or for debugging
purposes

www.querity.cz
Redundant Assertions
public void testSomething() {
…....
assertEquals(10.0, updatedEntity.getQuantity(), Double.MAX_VALUE);
assertTrue(true);
}

public void testSomething() {
…....
assertTrue(existingServiceEntryTOs.size() == 0);
assertNotNull(existingServiceEntryTOs);
}

www.querity.cz
Using the Wrong Assert
►There is more than assertTrue
►java assert keyword

www.querity.cz
Using the Wrong Assert
assertTrue("Objects must be the same", expected == actual);
assertTrue("Objects must be equal", expected.equals(actual));
assertTrue("Object must be null", actual == null);
assertTrue("Object must not be null", actual != null);

assertSame("Objects must be the same", expected, actual);
assertEquals("Objects must be equal", expected, actual);
assertNull("Object must be null", actual);
assertNotNull("Object must not be null", actual);

www.querity.cz
Only Easy/Happy Path Tests
►Only expected behavior is tested
►Only easy to verify things are tested
►The Liar, The Dodger, Success Against All
Odds

www.querity.cz
Only Easy/Happy Path Tests
@Test
public void testGoodCase()
{
Assert.assertEquals(2.0, Math.sqrt(4.0), 0.0);
}
@Test
public void testInteger()
{
Integer intToTest = new Integer(10);
Assert.assertEquals(intToTest.intValue(), 10);
}

www.querity.cz
Complex Tests
►Same rules like for production code
►Excessive Setup, The Giant, The Mockery,
The Nitpicker, The Stranger, The Free Ride,
The One, The Slow Poke

www.querity.cz
Complex Tests
In general, you should refactor a test until it
can be easily recognised to follow the
general structure:
► Set up
► Declare the expected results
► Excercise the unit under test
► Get the action results
► Assert that the actual results match the
expected results

www.querity.cz
(External) Dependencies
►External dependencies that code may need
to rely on to work correctly.
►Dependencies between tests – one test
prepares data for other one.
►Dependencies to object internal state
►The Inspector, Generous Leftovers, The
Local Hero, The Operating System
Evangelist, The Sequencer, Hidden
Dependency, The Peeping Tom

www.querity.cz
Catching Unexpected
Exceptions
►Test succeeds even if an exception is thrown
►The Liar, The Greedy Catcher
public void testCalculation() {
try {
deepThought.calculate();
assertEquals("Calculation wrong", 42, deepThought.getResult());
}
catch(CalculationException ex) {
Log.error("Calculation caused exception", ex);
}
}
www.querity.cz
Catching Unexpected
Exceptions

public void testCalculation() {
try {
deepThought.calculate();
assertEquals("Calculation wrong", 42, deepThought.getResult());
}
catch(CalculationException ex) {
fail("Calculation caused exception");
}
}

www.querity.cz
www.querity.cz
Mixing Production and Test
Code
►More complex packaging
►Ability to test package private methods

www.querity.cz
Programming is like sex. One mistake
and you have to support it for the rest of your life.
~Michael Sinz

www.querity.cz
www.querity.cz
Agenda
►Motivation
►What is automatic test
►Anti-patterns catalog
►Basic mistakes
►Best practices
►Summary
►Questions

www.querity.cz
Best Practices
►Same quality as production code
►Common sense
►No logger errors even from tests (The
Loudmouth)
►Use test coverage tools
►Do NOT be afraid to rewrite/delete
badly written complex tests
►TDD

www.querity.cz
Agenda
►Motivation
►What is automatic test
►Anti-patterns catalog
►Basic mistakes
►Best practices
►Summary
►Questions

www.querity.cz
Summary
►Do NOT repeat mistakes
►Manual testing is boring but false
alarms are pain as well

A good programmer is someone who always
looks both ways before crossing a one-way
street. ~Doug Linder

www.querity.cz
Agenda
►Motivation
►What is automatic test
►Anti-patterns catalog
►Examples
►Best practices
►Summary
►Questions

www.querity.cz
Links
►http://en.wikipedia.org/wiki/Software_testing
►http://www.exubero.com/junit/antipatterns.html
► http://blog.james-carr.org/2006/11/03/tdd-anti-patterns/

www.querity.cz
Questions …
… and maybe answers

www.querity.cz
Thank you

Ing. Jiří Kiml ,
21/11/2013, ZCU

www.querity.cz

Mais conteúdo relacionado

Semelhante a Test antipatterns

Mutation testing for a safer Future
Mutation testing for a safer FutureMutation testing for a safer Future
Mutation testing for a safer FutureCocoaHeads France
 
Automated Frontend Testing
Automated Frontend TestingAutomated Frontend Testing
Automated Frontend TestingNeil Crosby
 
The Art of Identifying Vulnerabilities - CascadiaFest 2015
The Art of Identifying Vulnerabilities  - CascadiaFest 2015The Art of Identifying Vulnerabilities  - CascadiaFest 2015
The Art of Identifying Vulnerabilities - CascadiaFest 2015Adam Baldwin
 
Aaron Bedra - Effective Software Security Teams
Aaron Bedra - Effective Software Security TeamsAaron Bedra - Effective Software Security Teams
Aaron Bedra - Effective Software Security Teamscentralohioissa
 
Static Analysis in IDEA
Static Analysis in IDEAStatic Analysis in IDEA
Static Analysis in IDEAHamletDRC
 
White-box Unit Test Generation with Microsoft IntelliTest
White-box Unit Test Generation with Microsoft IntelliTestWhite-box Unit Test Generation with Microsoft IntelliTest
White-box Unit Test Generation with Microsoft IntelliTestDávid Honfi
 
PVS-Studio. Static code analyzer. Windows/Linux, C/C++/C#. 2017
PVS-Studio. Static code analyzer. Windows/Linux, C/C++/C#. 2017PVS-Studio. Static code analyzer. Windows/Linux, C/C++/C#. 2017
PVS-Studio. Static code analyzer. Windows/Linux, C/C++/C#. 2017Andrey Karpov
 
findbugs Bernhard Merkle
findbugs Bernhard Merklefindbugs Bernhard Merkle
findbugs Bernhard Merklebmerkle
 
Automated code audits
Automated code auditsAutomated code audits
Automated code auditsDamien Seguy
 
Static analysis as means of improving code quality
Static analysis as means of improving code quality Static analysis as means of improving code quality
Static analysis as means of improving code quality Andrey Karpov
 
Building unit tests correctly
Building unit tests correctlyBuilding unit tests correctly
Building unit tests correctlyDror Helper
 
Automated code audits
Automated code auditsAutomated code audits
Automated code auditsexakat
 
Accord.Net: Looking for a Bug that Could Help Machines Conquer Humankind
Accord.Net: Looking for a Bug that Could Help Machines Conquer HumankindAccord.Net: Looking for a Bug that Could Help Machines Conquer Humankind
Accord.Net: Looking for a Bug that Could Help Machines Conquer HumankindPVS-Studio
 
Mind your language(s), A Discussion about Languages and Security
Mind your language(s), A Discussion about Languages and SecurityMind your language(s), A Discussion about Languages and Security
Mind your language(s), A Discussion about Languages and SecurityAdaCore
 
How to write clean & testable code without losing your mind
How to write clean & testable code without losing your mindHow to write clean & testable code without losing your mind
How to write clean & testable code without losing your mindAndreas Czakaj
 
Automating to Augment Testing
Automating to Augment TestingAutomating to Augment Testing
Automating to Augment TestingAlan Richardson
 
Why Windows 8 drivers are buggy
Why Windows 8 drivers are buggyWhy Windows 8 drivers are buggy
Why Windows 8 drivers are buggyAndrey Karpov
 
Analyzing the Dolphin-emu project
Analyzing the Dolphin-emu projectAnalyzing the Dolphin-emu project
Analyzing the Dolphin-emu projectPVS-Studio
 

Semelhante a Test antipatterns (20)

Price of an Error
Price of an ErrorPrice of an Error
Price of an Error
 
Mutation testing for a safer Future
Mutation testing for a safer FutureMutation testing for a safer Future
Mutation testing for a safer Future
 
Automated Frontend Testing
Automated Frontend TestingAutomated Frontend Testing
Automated Frontend Testing
 
The Art of Identifying Vulnerabilities - CascadiaFest 2015
The Art of Identifying Vulnerabilities  - CascadiaFest 2015The Art of Identifying Vulnerabilities  - CascadiaFest 2015
The Art of Identifying Vulnerabilities - CascadiaFest 2015
 
Aaron Bedra - Effective Software Security Teams
Aaron Bedra - Effective Software Security TeamsAaron Bedra - Effective Software Security Teams
Aaron Bedra - Effective Software Security Teams
 
Static Analysis in IDEA
Static Analysis in IDEAStatic Analysis in IDEA
Static Analysis in IDEA
 
White-box Unit Test Generation with Microsoft IntelliTest
White-box Unit Test Generation with Microsoft IntelliTestWhite-box Unit Test Generation with Microsoft IntelliTest
White-box Unit Test Generation with Microsoft IntelliTest
 
PVS-Studio. Static code analyzer. Windows/Linux, C/C++/C#. 2017
PVS-Studio. Static code analyzer. Windows/Linux, C/C++/C#. 2017PVS-Studio. Static code analyzer. Windows/Linux, C/C++/C#. 2017
PVS-Studio. Static code analyzer. Windows/Linux, C/C++/C#. 2017
 
findbugs Bernhard Merkle
findbugs Bernhard Merklefindbugs Bernhard Merkle
findbugs Bernhard Merkle
 
Automated code audits
Automated code auditsAutomated code audits
Automated code audits
 
Static analysis as means of improving code quality
Static analysis as means of improving code quality Static analysis as means of improving code quality
Static analysis as means of improving code quality
 
Building unit tests correctly
Building unit tests correctlyBuilding unit tests correctly
Building unit tests correctly
 
Automated code audits
Automated code auditsAutomated code audits
Automated code audits
 
Accord.Net: Looking for a Bug that Could Help Machines Conquer Humankind
Accord.Net: Looking for a Bug that Could Help Machines Conquer HumankindAccord.Net: Looking for a Bug that Could Help Machines Conquer Humankind
Accord.Net: Looking for a Bug that Could Help Machines Conquer Humankind
 
Mind your language(s), A Discussion about Languages and Security
Mind your language(s), A Discussion about Languages and SecurityMind your language(s), A Discussion about Languages and Security
Mind your language(s), A Discussion about Languages and Security
 
How to write clean & testable code without losing your mind
How to write clean & testable code without losing your mindHow to write clean & testable code without losing your mind
How to write clean & testable code without losing your mind
 
Automating to Augment Testing
Automating to Augment TestingAutomating to Augment Testing
Automating to Augment Testing
 
JUNit Presentation
JUNit PresentationJUNit Presentation
JUNit Presentation
 
Why Windows 8 drivers are buggy
Why Windows 8 drivers are buggyWhy Windows 8 drivers are buggy
Why Windows 8 drivers are buggy
 
Analyzing the Dolphin-emu project
Analyzing the Dolphin-emu projectAnalyzing the Dolphin-emu project
Analyzing the Dolphin-emu project
 

Último

[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
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 Takeoffsammart93
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Bhuvaneswari Subramani
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
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, Adobeapidays
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxRemote DBA Services
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 

Último (20)

[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
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
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
+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...
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
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
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 

Test antipatterns

  • 1. Automatic test anti-patterns Ing. Jiří Kiml, 20/11/2013, ZCU www.querity.cz
  • 2. Agenda ►Motivation ►What is automatic test ►Anti-patterns catalog ►Basic mistakes ►Best practices ►Summary ►Questions www.querity.cz
  • 3. Motivation Any fool can write code that a computer can understand. Good programmers write code that humans can understand. ~Martin Fowler ►Detect REAL bugs early ►Avoid boring regression tests ►Better design, api documentation ►Code quality www.querity.cz
  • 5. Agenda ►Motivation ►What is automatic test ►Anti-patterns catalog ►Basic mistakes ►Best practices ►Summary ►Questions www.querity.cz
  • 6. What is automatic test ►No definition in wiki ;-( ►….. example in eclipse www.querity.cz
  • 7. Agenda ►Motivation ►What is automatic test ►Anti-patterns catalog ►Basic mistakes ►Best practices ►Summary ►Questions www.querity.cz
  • 8. Anti-patterns catalog The Liar, Excessive Setup, The Giant, The Mockery, The Inspector, Generous Leftovers, The Local Hero, The Nitpicker, The Secret Catcher, The Dodger, The Loudmouth, The Greedy Catcher The Sequencer, Hidden Dependency The Enumerator, The Stranger, The Operating System Evangelist, Success Against All Odds, The Free Ride The One, The Peeping Tom The Slow Poke www.querity.cz
  • 10. Agenda ►Motivation ►What is automatic test ►Anti-patterns catalog ►Basic mistakes ►Best practices ►Summary ►Questions www.querity.cz
  • 11. Basic mistakes ►No tests ►Manual (missing) Assertions ►Redundant Assertions ►Using the Wrong Assert ►Only Easy/Happy Path Tests ►Complex Tests ►External Dependencies ►Catching Unexpected Exceptions ►Mixing Production and Test Code www.querity.cz
  • 12. No tests ►Still common in many companies ►“It is to expensive to write tests.” ►“We will write tests later”. (never) ►The Liar, Success Against All Odds www.querity.cz
  • 13. No tests // TODO: This tests need to be activated when nightly db-reset is done! @Ignore @Test public void testXXX() { ... } @Test public void testYYY() { // TODO implement me } www.querity.cz
  • 14. Manual (missing) Assertions ►Sysout instead of assert ►Why not just use a debugger? ►The Secret Catcher "Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." Brian W. Kernighan www.querity.cz
  • 15. Manual (missing) Assertions public void testCalculation() { deepThought.calculate(); System.out.println(deepThought.getResult()); } public void testCalculation() { deepThought.calculate(); assertEquals(42, deepThought.getResult()); } www.querity.cz
  • 16. Redundant Assertions ►Always true or always false assertions ►Introduced by mistake or for debugging purposes www.querity.cz
  • 17. Redundant Assertions public void testSomething() { ….... assertEquals(10.0, updatedEntity.getQuantity(), Double.MAX_VALUE); assertTrue(true); } public void testSomething() { ….... assertTrue(existingServiceEntryTOs.size() == 0); assertNotNull(existingServiceEntryTOs); } www.querity.cz
  • 18. Using the Wrong Assert ►There is more than assertTrue ►java assert keyword www.querity.cz
  • 19. Using the Wrong Assert assertTrue("Objects must be the same", expected == actual); assertTrue("Objects must be equal", expected.equals(actual)); assertTrue("Object must be null", actual == null); assertTrue("Object must not be null", actual != null); assertSame("Objects must be the same", expected, actual); assertEquals("Objects must be equal", expected, actual); assertNull("Object must be null", actual); assertNotNull("Object must not be null", actual); www.querity.cz
  • 20. Only Easy/Happy Path Tests ►Only expected behavior is tested ►Only easy to verify things are tested ►The Liar, The Dodger, Success Against All Odds www.querity.cz
  • 21. Only Easy/Happy Path Tests @Test public void testGoodCase() { Assert.assertEquals(2.0, Math.sqrt(4.0), 0.0); } @Test public void testInteger() { Integer intToTest = new Integer(10); Assert.assertEquals(intToTest.intValue(), 10); } www.querity.cz
  • 22. Complex Tests ►Same rules like for production code ►Excessive Setup, The Giant, The Mockery, The Nitpicker, The Stranger, The Free Ride, The One, The Slow Poke www.querity.cz
  • 23. Complex Tests In general, you should refactor a test until it can be easily recognised to follow the general structure: ► Set up ► Declare the expected results ► Excercise the unit under test ► Get the action results ► Assert that the actual results match the expected results www.querity.cz
  • 24. (External) Dependencies ►External dependencies that code may need to rely on to work correctly. ►Dependencies between tests – one test prepares data for other one. ►Dependencies to object internal state ►The Inspector, Generous Leftovers, The Local Hero, The Operating System Evangelist, The Sequencer, Hidden Dependency, The Peeping Tom www.querity.cz
  • 25. Catching Unexpected Exceptions ►Test succeeds even if an exception is thrown ►The Liar, The Greedy Catcher public void testCalculation() { try { deepThought.calculate(); assertEquals("Calculation wrong", 42, deepThought.getResult()); } catch(CalculationException ex) { Log.error("Calculation caused exception", ex); } } www.querity.cz
  • 26. Catching Unexpected Exceptions public void testCalculation() { try { deepThought.calculate(); assertEquals("Calculation wrong", 42, deepThought.getResult()); } catch(CalculationException ex) { fail("Calculation caused exception"); } } www.querity.cz
  • 28. Mixing Production and Test Code ►More complex packaging ►Ability to test package private methods www.querity.cz
  • 29. Programming is like sex. One mistake and you have to support it for the rest of your life. ~Michael Sinz www.querity.cz
  • 31. Agenda ►Motivation ►What is automatic test ►Anti-patterns catalog ►Basic mistakes ►Best practices ►Summary ►Questions www.querity.cz
  • 32. Best Practices ►Same quality as production code ►Common sense ►No logger errors even from tests (The Loudmouth) ►Use test coverage tools ►Do NOT be afraid to rewrite/delete badly written complex tests ►TDD www.querity.cz
  • 33. Agenda ►Motivation ►What is automatic test ►Anti-patterns catalog ►Basic mistakes ►Best practices ►Summary ►Questions www.querity.cz
  • 34. Summary ►Do NOT repeat mistakes ►Manual testing is boring but false alarms are pain as well A good programmer is someone who always looks both ways before crossing a one-way street. ~Doug Linder www.querity.cz
  • 35. Agenda ►Motivation ►What is automatic test ►Anti-patterns catalog ►Examples ►Best practices ►Summary ►Questions www.querity.cz
  • 37. Questions … … and maybe answers www.querity.cz
  • 38. Thank you Ing. Jiří Kiml , 21/11/2013, ZCU www.querity.cz