SlideShare une entreprise Scribd logo
1  sur  22
Télécharger pour lire hors ligne
Dijkstra, The Humble Programmer 1972
Gute Tests
● Mit jedem Test stellen wir sicher, dass die getestete
Funktionalität korrekt umgesetzt ist
● Hoffnung, dass ähnliche Fälle genauso gut funktionieren
(Äquivalenzklassen)
● Änderungen werden leichter möglich, weil sichergestellt wird,
dass die bestehende Funktionalität nicht kaputt geht
● Tests sind die aktuellste Dokumentation
● Jeder Test erzählt eine Geschichte über was passiert und
was zu erwarten ist.
●
Böse Tests
● Fragile Tests: kleine Änderung in der
Implementierung => viele Tests betroffen
● Redundante Tests => Balast
● Triviale Tests
● Unvollständige Tests => falsche Sicherheit
● Tests ohne Asserts
No Assertions
IResult result = format.execute();
System.out.println(result.size());
Iterator iter = result.iterator();
while (iter.hasNext()) {
IResult r = (IResult) iter.next();
System.out.println(r.getMessage());
}
No Assertions
(verbessert)
IResult result = format.execute();
assertThat(result.size()).isEqualTo(3); 1
Iterator iter = result.iterator();
while (iter.hasNext()) {
IResult r = (IResult) iter.next();
assertThat(r.getMessage()).contains("error"); 2
}
Get- Setter
public void testSetGetParam() throws Exception {
String[] tests = {"a", "aaa", "---",
"23121313", "", null};
for (int i = 0; i < tests.length; i++) {
adapter.setParam(tests[i]);
assertEquals(tests[i], adapter.getParam());
}
}
Happy Path
public class FizzBuzzTest {
@Test
public void testMultipleOfThreeAndFivePrintsFizzBuzz() {
assertEquals("FizzBuzz", FizzBuzz.getResult(15));
}
@Test
public void testMultipleOfThreeOnlyPrintsFizz() {
assertEquals("Fizz", FizzBuzz.getResult(93));
}
Happy Path
(verbessert)
@RunWith(JUnitParamsRunner.class)
public class FizzBuzzJUnitTest {
@Test
@Parameters(value = {"15", "30", "75"})
public void testMultipleOfThreeAndFivePrintsFizzBuzz(
int multipleOf3And5) {
assertEquals("FizzBuzz", FizzBuzz.getResult(multipleOf3And5));
}
@Test
@Parameters(value = {"9", "36", "81"})
public void testMultipleOfThreeOnlyPrintsFizz(...
@Test
@Parameters(value = {"10", "55", "100"})
public void testMultipleOfFiveOnlyPrintsBuzz(...
@Test
@Parameters(value = {"2", "16", "23", "47", "52", ...
public void testInputOfEightPrintsTheNumber(...
}
Not Enough Testing
@Test
public class PagerTest {
private static final int PER_PAGE = 10;
public void shouldGiveOffsetZeroWhenOnZeroPage() {
Pager pager = new Pager(PER_PAGE);
assertThat(pager.getOffset()).isEqualTo(0);
}
public void shouldIncreaseOffsetWhenGoingToPageOne() {
Pager pager = new Pager(PER_PAGE);
pager.goToNextPage();
assertThat(pager.getOffset()).isEqualTo(PER_PAGE);
}
}
Not Enough Testing
(verbessert)
Zero, One and Many
Auskommentieren
//@Test
public void testTeaserWithBildPlusMarker()
{
String url = urlBuilder.setBaseUrl(HTTP_START_PATH +
TEASERREIHE_BILDPLUS_MARKER_PATH.setView("module".build();
driver.get(url);
// Teaserreihe
WebElement teaserReiheElement = getRootElement();
BTOTeaserReihe_modulePO teaserReihePO =
new BTOTeaserReihe_modulePO(teaserReiheElement);
List<Resource_teaserPO> teaserPOs =
teaserReihePO.getTeaserPOs();
assertNotNull("Teaser-Page-Objekte fehlen", teaserPOs);
assertEquals(1, teaserPOs.size());
}
(Aus bildcms JSP-Tests)
Auskommentieren
(verbessert)
@Test @Ignore //TODO momentan nicht testbar auf Testsystem
public void testTeaserWithBildPlusMarker()
{
String url = urlBuilder.setBaseUrl(HTTP_START_PATH +
TEASERREIHE_BILDPLUS_MARKER_PATH.setView("module".build();
driver.get(url);
// Teaserreihe
WebElement teaserReiheElement = getRootElement();
BTOTeaserReihe_modulePO teaserReihePO =
new BTOTeaserReihe_modulePO(teaserReiheElement);
List<Resource_teaserPO> teaserPOs =
teaserReihePO.getTeaserPOs();
assertNotNull("Teaser-Page-Objekte fehlen", teaserPOs);
assertEquals(1, teaserPOs.size());
}
Expecting Exceptions Anywhere
@Test(expected=IndexOutOfBoundsException.class)
public void testMyList() {
MyList<Integer> list = new MyList<Integer>();
list.add(1);
list.add(2);
list.add(3);
list.add(3);
list.add(4);
assertTrue(4 == list.get(4));
assertTrue(2 == list.get(1));
assertTrue(3 == list.get(2));
list.get(6);
}
Expecting Exceptions Anywhere
(verbessert)
● Tests aufteilen (Split)
● Exception-Test Lokalisieren
Assertions should be Merciless
@Test
public void shouldRemoveEmailsByState() {
//given
Email pending = createAndSaveEmail("pending","content pending",
"abc@def.com", Email.PENDING);
Email failed = createAndSaveEmail("failed","content failed",
"abc@def.com", Email.FAILED);
Email sent = createAndSaveEmail("sent","content sent",
"abc@def.com", Email.SENT);
//when
emailDAO.removeByState(Email.FAILED);
//then
assertThat(emailDAO.findAll()).excludes(failed);
}
Assertions should be Merciless
(verbessert)
assertThat(emailDAO.findAll(),
contains(pending, sent))
Is Mockito Working Fine?
@Test
public void testFormUpdate() {
// given
Form f = Mockito.mock(Form.class);
Mockito.when(
f.isUpdateAllowed()).thenReturn(true);
// when
boolean result = f.isUpdateAllowed();
// then
assertTrue(result);
}
@Test
public void will_getChangSecurityQuestRgtAndDetails_if_AdvUserhasRuleId25(){
User user = createUser(userId);
user.setAdvanced(true);
PasswordRuleDto passwordRuleDto = new PasswordRuleDto();
passwordRuleDto.setPasswordRuleId(rulId25);
List<PasswordRuleDto> passwordRules = new ArrayList<PasswordRuleDto>();
passwordRules.add(passwordRuleDto);
given(currentUser.getUser()).thenReturn(user);
given(userDAO.readByPrimaryKey(userId)).thenReturn(user);
given(passwordBean.getPasswordRules()).thenReturn(passwordRules);
UserSecurityQuestionDto dto = userChangeSecurityQuestionBean
.getChangSecurityQuestionRgtAndDetails();
assertNotNull(dto.getEmail());
assertNotNull(dto.getFirstName());
assertNotNull(dto.getLastName());
assertEquals(dto.isChangeSecurityQuestion(), true);
}
Why formatting helps
@Test
public void will_getChangSecurityQuestRgtAndDetails_if_AdvUserhasRuleId25(){
// given
User user = createUser(userId);
user.setAdvanced(true);
PasswordRuleDto passwordRuleDto = new PasswordRuleDto();
passwordRuleDto.setPasswordRuleId(rulId25);
List<PasswordRuleDto> passwordRules = new ArrayList<PasswordRuleDto>();
passwordRules.add(passwordRuleDto);
given(currentUser.getUser()).willReturn(user);
given(userDAO.readByPrimaryKey(userId)).willReturn(user);
given(passwordBean.getPasswordRules()).willReturn(passwordRules);
// when
UserSecurityQuestionDto dto = userChangeSecurityQuestionBean
.getChangSecurityQuestionRgtAndDetails();
// then
assertNotNull(dto.getEmail());
assertNotNull(dto.getFirstName());
assertNotNull(dto.getLastName());
assertEquals(dto.isChangeSecurityQuestion(), true);
}
Why formatting helps
(verbessert)
When a Test Name Lies
Should is Better than Test
public void testInsertNewValues() {
//given
//when
reportRepository.updateReport(ReportColumn.DATE,
ReportColumn.PLACE, reportMap(BigDecimal.TEN));
reportRepository.updateReport(ReportColumn.DATE,
ReportColumn.PLACE, reportMap(new BigDecimal("5")));
//then
assertThat(reportRepository
.getCount(ReportColumn.DATE, ReportColumn.PLACE))
.isEqualTo(1);
}
When a Test Name Lies
Should is Better than Test
(korrigiert)
public void shouldOverrideOldReportWithNewValues() {
//given
//when
reportRepository.updateReport(ReportColumn.DATE,
ReportColumn.PLACE, reportMap(BigDecimal.TEN));
reportRepository.updateReport(ReportColumn.DATE,
ReportColumn.PLACE, reportMap(new BigDecimal("5")));
//then
assertThat(reportRepository
.getCount(ReportColumn.DATE, ReportColumn.PLACE))
.isEqualTo(1);
}

Contenu connexe

Tendances

Unit Testing Presentation
Unit Testing PresentationUnit Testing Presentation
Unit Testing Presentation
nicobn
 
Python Unit Test
Python Unit TestPython Unit Test
Python Unit Test
David Xie
 
Unit Testing using PHPUnit
Unit Testing using  PHPUnitUnit Testing using  PHPUnit
Unit Testing using PHPUnit
varuntaliyan
 
Beginning PHPUnit
Beginning PHPUnitBeginning PHPUnit
Beginning PHPUnit
Jace Ju
 

Tendances (20)

The Ring programming language version 1.9 book - Part 92 of 210
The Ring programming language version 1.9 book - Part 92 of 210The Ring programming language version 1.9 book - Part 92 of 210
The Ring programming language version 1.9 book - Part 92 of 210
 
Mutation Testing: Testing your tests
Mutation Testing: Testing your testsMutation Testing: Testing your tests
Mutation Testing: Testing your tests
 
Phpunit testing
Phpunit testingPhpunit testing
Phpunit testing
 
GMock framework
GMock frameworkGMock framework
GMock framework
 
PL/SQL Unit Testing Can Be Fun
PL/SQL Unit Testing Can Be FunPL/SQL Unit Testing Can Be Fun
PL/SQL Unit Testing Can Be Fun
 
The secret unit testing tools no one ever told you about
The secret unit testing tools no one ever told you aboutThe secret unit testing tools no one ever told you about
The secret unit testing tools no one ever told you about
 
PhpUnit Best Practices
PhpUnit Best PracticesPhpUnit Best Practices
PhpUnit Best Practices
 
Angular testing
Angular testingAngular testing
Angular testing
 
Nested loop join technique - part2
Nested loop join technique - part2Nested loop join technique - part2
Nested loop join technique - part2
 
Unit testing patterns for concurrent code
Unit testing patterns for concurrent codeUnit testing patterns for concurrent code
Unit testing patterns for concurrent code
 
Unit Testing Presentation
Unit Testing PresentationUnit Testing Presentation
Unit Testing Presentation
 
Python Unit Test
Python Unit TestPython Unit Test
Python Unit Test
 
Unit Testing in Angular(7/8/9) Using Jasmine and Karma Part-2
Unit Testing in Angular(7/8/9) Using Jasmine and Karma Part-2Unit Testing in Angular(7/8/9) Using Jasmine and Karma Part-2
Unit Testing in Angular(7/8/9) Using Jasmine and Karma Part-2
 
Unit Testing using PHPUnit
Unit Testing using  PHPUnitUnit Testing using  PHPUnit
Unit Testing using PHPUnit
 
UPC Testing talk 2
UPC Testing talk 2UPC Testing talk 2
UPC Testing talk 2
 
15 tips to improve your unit tests (Droidcon Berlin 2016 Barcamp)
15 tips to improve your unit tests (Droidcon Berlin 2016 Barcamp)15 tips to improve your unit tests (Droidcon Berlin 2016 Barcamp)
15 tips to improve your unit tests (Droidcon Berlin 2016 Barcamp)
 
Easy Button
Easy ButtonEasy Button
Easy Button
 
PHPUnit best practices presentation
PHPUnit best practices presentationPHPUnit best practices presentation
PHPUnit best practices presentation
 
Beginning PHPUnit
Beginning PHPUnitBeginning PHPUnit
Beginning PHPUnit
 
Why Kotlin - Apalon Kotlin Sprint Part 1
Why Kotlin - Apalon Kotlin Sprint Part 1Why Kotlin - Apalon Kotlin Sprint Part 1
Why Kotlin - Apalon Kotlin Sprint Part 1
 

En vedette

I rev. ind y ii rev. ind.
I rev. ind y ii rev. ind.I rev. ind y ii rev. ind.
I rev. ind y ii rev. ind.
Ayelenvargas10
 
Company Profile Jaya Plumbing
Company Profile Jaya PlumbingCompany Profile Jaya Plumbing
Company Profile Jaya Plumbing
Lutfi Shebubakar
 
Mandibular Angle Fractures
Mandibular Angle FracturesMandibular Angle Fractures
Mandibular Angle Fractures
Ahmed Adawy
 

En vedette (20)

Tns au colloque communication verte
Tns au colloque communication verteTns au colloque communication verte
Tns au colloque communication verte
 
I rev. ind y ii rev. ind.
I rev. ind y ii rev. ind.I rev. ind y ii rev. ind.
I rev. ind y ii rev. ind.
 
SNV_RAV_IC_SGB_2015-2016
SNV_RAV_IC_SGB_2015-2016SNV_RAV_IC_SGB_2015-2016
SNV_RAV_IC_SGB_2015-2016
 
La educación en jovellanos
La educación en jovellanosLa educación en jovellanos
La educación en jovellanos
 
Eu et les ptom contexte environnemental mecki kronen
Eu et les ptom contexte environnemental mecki kronenEu et les ptom contexte environnemental mecki kronen
Eu et les ptom contexte environnemental mecki kronen
 
ijoms published, Research Gate
ijoms  published, Research Gateijoms  published, Research Gate
ijoms published, Research Gate
 
Educación permante EQUIPO 3
Educación permante EQUIPO 3Educación permante EQUIPO 3
Educación permante EQUIPO 3
 
Sludge thermal treatment - High temperature fluidized bed
Sludge thermal treatment - High temperature fluidized bed Sludge thermal treatment - High temperature fluidized bed
Sludge thermal treatment - High temperature fluidized bed
 
Saffola Chinese Masala Oats Case Study
Saffola Chinese Masala Oats Case StudySaffola Chinese Masala Oats Case Study
Saffola Chinese Masala Oats Case Study
 
Company Profile Jaya Plumbing
Company Profile Jaya PlumbingCompany Profile Jaya Plumbing
Company Profile Jaya Plumbing
 
II-SDV 2016 Srinivasan Parthiban - KOL Analytics from Biomedical Literature
II-SDV 2016 Srinivasan Parthiban - KOL Analytics from Biomedical LiteratureII-SDV 2016 Srinivasan Parthiban - KOL Analytics from Biomedical Literature
II-SDV 2016 Srinivasan Parthiban - KOL Analytics from Biomedical Literature
 
Exposicion de la edad moderna
Exposicion de la  edad modernaExposicion de la  edad moderna
Exposicion de la edad moderna
 
Mandibular Angle Fractures
Mandibular Angle FracturesMandibular Angle Fractures
Mandibular Angle Fractures
 
El pollo a la brasa - Insights del Consumidor
El pollo a la brasa - Insights del ConsumidorEl pollo a la brasa - Insights del Consumidor
El pollo a la brasa - Insights del Consumidor
 
Retrobulbar hemorrhage by Somu Venkatesh
Retrobulbar hemorrhage by Somu VenkateshRetrobulbar hemorrhage by Somu Venkatesh
Retrobulbar hemorrhage by Somu Venkatesh
 
Reconstruction of mandibular defects
Reconstruction of mandibular defectsReconstruction of mandibular defects
Reconstruction of mandibular defects
 
A2 Level Media Studies Production Planning
A2 Level Media Studies Production PlanningA2 Level Media Studies Production Planning
A2 Level Media Studies Production Planning
 
441 preso airbnb
441 preso   airbnb441 preso   airbnb
441 preso airbnb
 
Tesla motors
Tesla motorsTesla motors
Tesla motors
 
Slack- a presentation
Slack- a presentationSlack- a presentation
Slack- a presentation
 

Similaire à Good Tests Bad 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
Tomek Kaczanowski
 

Similaire à Good Tests Bad Tests (20)

Confitura 2012 Bad Tests, Good Tests
Confitura 2012 Bad Tests, Good TestsConfitura 2012 Bad Tests, Good Tests
Confitura 2012 Bad Tests, Good Tests
 
Testing with VS2010 - A Bugs Life
Testing with VS2010 - A Bugs LifeTesting with VS2010 - A Bugs Life
Testing with VS2010 - A Bugs Life
 
GeeCON 2012 Bad Tests, Good Tests
GeeCON 2012 Bad Tests, Good TestsGeeCON 2012 Bad Tests, Good Tests
GeeCON 2012 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
 
Developer Test - Things to Know
Developer Test - Things to KnowDeveloper Test - Things to Know
Developer Test - Things to Know
 
1 aleksandr gritsevski - attd example using
1   aleksandr gritsevski - attd example using1   aleksandr gritsevski - attd example using
1 aleksandr gritsevski - attd example using
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests
 
We Love Performance! How Tic Toc Games Uses ECS in Mobile Puzzle Games
We Love Performance! How Tic Toc Games Uses ECS in Mobile Puzzle GamesWe Love Performance! How Tic Toc Games Uses ECS in Mobile Puzzle Games
We Love Performance! How Tic Toc Games Uses ECS in Mobile Puzzle Games
 
Introduction to nsubstitute
Introduction to nsubstituteIntroduction to nsubstitute
Introduction to nsubstitute
 
Pragmatic unittestingwithj unit
Pragmatic unittestingwithj unitPragmatic unittestingwithj unit
Pragmatic unittestingwithj unit
 
How to write clean tests
How to write clean testsHow to write clean tests
How to write clean tests
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
Presentation Unit Testing process
Presentation Unit Testing processPresentation Unit Testing process
Presentation Unit Testing process
 
"Unit Testing for Mobile App" by Fandy Gotama (OLX Indonesia)
"Unit Testing for Mobile App" by Fandy Gotama  (OLX Indonesia)"Unit Testing for Mobile App" by Fandy Gotama  (OLX Indonesia)
"Unit Testing for Mobile App" by Fandy Gotama (OLX Indonesia)
 
Tech In Asia PDC 2017 - Best practice unit testing in mobile apps
Tech In Asia PDC 2017 - Best practice unit testing in mobile appsTech In Asia PDC 2017 - Best practice unit testing in mobile apps
Tech In Asia PDC 2017 - Best practice unit testing in mobile apps
 
Junit and testNG
Junit and testNGJunit and testNG
Junit and testNG
 
The secret unit testing tools no one has ever told you about
The secret unit testing tools no one has ever told you aboutThe secret unit testing tools no one has ever told you about
The secret unit testing tools no one has ever told you about
 
Php tests tips
Php tests tipsPhp tests tips
Php tests tips
 
Test Infected Presentation
Test Infected PresentationTest Infected Presentation
Test Infected Presentation
 
Unit testing
Unit testingUnit testing
Unit testing
 

Dernier

AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 

Dernier (20)

Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 

Good Tests Bad Tests

  • 1.
  • 2. Dijkstra, The Humble Programmer 1972
  • 3. Gute Tests ● Mit jedem Test stellen wir sicher, dass die getestete Funktionalität korrekt umgesetzt ist ● Hoffnung, dass ähnliche Fälle genauso gut funktionieren (Äquivalenzklassen) ● Änderungen werden leichter möglich, weil sichergestellt wird, dass die bestehende Funktionalität nicht kaputt geht ● Tests sind die aktuellste Dokumentation ● Jeder Test erzählt eine Geschichte über was passiert und was zu erwarten ist. ●
  • 4. Böse Tests ● Fragile Tests: kleine Änderung in der Implementierung => viele Tests betroffen ● Redundante Tests => Balast ● Triviale Tests ● Unvollständige Tests => falsche Sicherheit ● Tests ohne Asserts
  • 5. No Assertions IResult result = format.execute(); System.out.println(result.size()); Iterator iter = result.iterator(); while (iter.hasNext()) { IResult r = (IResult) iter.next(); System.out.println(r.getMessage()); }
  • 6. No Assertions (verbessert) IResult result = format.execute(); assertThat(result.size()).isEqualTo(3); 1 Iterator iter = result.iterator(); while (iter.hasNext()) { IResult r = (IResult) iter.next(); assertThat(r.getMessage()).contains("error"); 2 }
  • 7. Get- Setter public void testSetGetParam() throws Exception { String[] tests = {"a", "aaa", "---", "23121313", "", null}; for (int i = 0; i < tests.length; i++) { adapter.setParam(tests[i]); assertEquals(tests[i], adapter.getParam()); } }
  • 8. Happy Path public class FizzBuzzTest { @Test public void testMultipleOfThreeAndFivePrintsFizzBuzz() { assertEquals("FizzBuzz", FizzBuzz.getResult(15)); } @Test public void testMultipleOfThreeOnlyPrintsFizz() { assertEquals("Fizz", FizzBuzz.getResult(93)); }
  • 9. Happy Path (verbessert) @RunWith(JUnitParamsRunner.class) public class FizzBuzzJUnitTest { @Test @Parameters(value = {"15", "30", "75"}) public void testMultipleOfThreeAndFivePrintsFizzBuzz( int multipleOf3And5) { assertEquals("FizzBuzz", FizzBuzz.getResult(multipleOf3And5)); } @Test @Parameters(value = {"9", "36", "81"}) public void testMultipleOfThreeOnlyPrintsFizz(... @Test @Parameters(value = {"10", "55", "100"}) public void testMultipleOfFiveOnlyPrintsBuzz(... @Test @Parameters(value = {"2", "16", "23", "47", "52", ... public void testInputOfEightPrintsTheNumber(... }
  • 10. Not Enough Testing @Test public class PagerTest { private static final int PER_PAGE = 10; public void shouldGiveOffsetZeroWhenOnZeroPage() { Pager pager = new Pager(PER_PAGE); assertThat(pager.getOffset()).isEqualTo(0); } public void shouldIncreaseOffsetWhenGoingToPageOne() { Pager pager = new Pager(PER_PAGE); pager.goToNextPage(); assertThat(pager.getOffset()).isEqualTo(PER_PAGE); } }
  • 12. Auskommentieren //@Test public void testTeaserWithBildPlusMarker() { String url = urlBuilder.setBaseUrl(HTTP_START_PATH + TEASERREIHE_BILDPLUS_MARKER_PATH.setView("module".build(); driver.get(url); // Teaserreihe WebElement teaserReiheElement = getRootElement(); BTOTeaserReihe_modulePO teaserReihePO = new BTOTeaserReihe_modulePO(teaserReiheElement); List<Resource_teaserPO> teaserPOs = teaserReihePO.getTeaserPOs(); assertNotNull("Teaser-Page-Objekte fehlen", teaserPOs); assertEquals(1, teaserPOs.size()); } (Aus bildcms JSP-Tests)
  • 13. Auskommentieren (verbessert) @Test @Ignore //TODO momentan nicht testbar auf Testsystem public void testTeaserWithBildPlusMarker() { String url = urlBuilder.setBaseUrl(HTTP_START_PATH + TEASERREIHE_BILDPLUS_MARKER_PATH.setView("module".build(); driver.get(url); // Teaserreihe WebElement teaserReiheElement = getRootElement(); BTOTeaserReihe_modulePO teaserReihePO = new BTOTeaserReihe_modulePO(teaserReiheElement); List<Resource_teaserPO> teaserPOs = teaserReihePO.getTeaserPOs(); assertNotNull("Teaser-Page-Objekte fehlen", teaserPOs); assertEquals(1, teaserPOs.size()); }
  • 14. Expecting Exceptions Anywhere @Test(expected=IndexOutOfBoundsException.class) public void testMyList() { MyList<Integer> list = new MyList<Integer>(); list.add(1); list.add(2); list.add(3); list.add(3); list.add(4); assertTrue(4 == list.get(4)); assertTrue(2 == list.get(1)); assertTrue(3 == list.get(2)); list.get(6); }
  • 15. Expecting Exceptions Anywhere (verbessert) ● Tests aufteilen (Split) ● Exception-Test Lokalisieren
  • 16. Assertions should be Merciless @Test public void shouldRemoveEmailsByState() { //given Email pending = createAndSaveEmail("pending","content pending", "abc@def.com", Email.PENDING); Email failed = createAndSaveEmail("failed","content failed", "abc@def.com", Email.FAILED); Email sent = createAndSaveEmail("sent","content sent", "abc@def.com", Email.SENT); //when emailDAO.removeByState(Email.FAILED); //then assertThat(emailDAO.findAll()).excludes(failed); }
  • 17. Assertions should be Merciless (verbessert) assertThat(emailDAO.findAll(), contains(pending, sent))
  • 18. Is Mockito Working Fine? @Test public void testFormUpdate() { // given Form f = Mockito.mock(Form.class); Mockito.when( f.isUpdateAllowed()).thenReturn(true); // when boolean result = f.isUpdateAllowed(); // then assertTrue(result); }
  • 19. @Test public void will_getChangSecurityQuestRgtAndDetails_if_AdvUserhasRuleId25(){ User user = createUser(userId); user.setAdvanced(true); PasswordRuleDto passwordRuleDto = new PasswordRuleDto(); passwordRuleDto.setPasswordRuleId(rulId25); List<PasswordRuleDto> passwordRules = new ArrayList<PasswordRuleDto>(); passwordRules.add(passwordRuleDto); given(currentUser.getUser()).thenReturn(user); given(userDAO.readByPrimaryKey(userId)).thenReturn(user); given(passwordBean.getPasswordRules()).thenReturn(passwordRules); UserSecurityQuestionDto dto = userChangeSecurityQuestionBean .getChangSecurityQuestionRgtAndDetails(); assertNotNull(dto.getEmail()); assertNotNull(dto.getFirstName()); assertNotNull(dto.getLastName()); assertEquals(dto.isChangeSecurityQuestion(), true); } Why formatting helps
  • 20. @Test public void will_getChangSecurityQuestRgtAndDetails_if_AdvUserhasRuleId25(){ // given User user = createUser(userId); user.setAdvanced(true); PasswordRuleDto passwordRuleDto = new PasswordRuleDto(); passwordRuleDto.setPasswordRuleId(rulId25); List<PasswordRuleDto> passwordRules = new ArrayList<PasswordRuleDto>(); passwordRules.add(passwordRuleDto); given(currentUser.getUser()).willReturn(user); given(userDAO.readByPrimaryKey(userId)).willReturn(user); given(passwordBean.getPasswordRules()).willReturn(passwordRules); // when UserSecurityQuestionDto dto = userChangeSecurityQuestionBean .getChangSecurityQuestionRgtAndDetails(); // then assertNotNull(dto.getEmail()); assertNotNull(dto.getFirstName()); assertNotNull(dto.getLastName()); assertEquals(dto.isChangeSecurityQuestion(), true); } Why formatting helps (verbessert)
  • 21. When a Test Name Lies Should is Better than Test public void testInsertNewValues() { //given //when reportRepository.updateReport(ReportColumn.DATE, ReportColumn.PLACE, reportMap(BigDecimal.TEN)); reportRepository.updateReport(ReportColumn.DATE, ReportColumn.PLACE, reportMap(new BigDecimal("5"))); //then assertThat(reportRepository .getCount(ReportColumn.DATE, ReportColumn.PLACE)) .isEqualTo(1); }
  • 22. When a Test Name Lies Should is Better than Test (korrigiert) public void shouldOverrideOldReportWithNewValues() { //given //when reportRepository.updateReport(ReportColumn.DATE, ReportColumn.PLACE, reportMap(BigDecimal.TEN)); reportRepository.updateReport(ReportColumn.DATE, ReportColumn.PLACE, reportMap(new BigDecimal("5"))); //then assertThat(reportRepository .getCount(ReportColumn.DATE, ReportColumn.PLACE)) .isEqualTo(1); }