SlideShare a Scribd company logo
1 of 22
Download to read offline
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);
}

More Related Content

What's hot

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 210Mahmoud Samir Fayed
 
Mutation Testing: Testing your tests
Mutation Testing: Testing your testsMutation Testing: Testing your tests
Mutation Testing: Testing your testsStephen Leigh
 
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 aboutDror Helper
 
PhpUnit Best Practices
PhpUnit Best PracticesPhpUnit Best Practices
PhpUnit Best PracticesEdorian
 
Unit testing patterns for concurrent code
Unit testing patterns for concurrent codeUnit testing patterns for concurrent code
Unit testing patterns for concurrent codeDror Helper
 
Unit Testing Presentation
Unit Testing PresentationUnit Testing Presentation
Unit Testing Presentationnicobn
 
Python Unit Test
Python Unit TestPython Unit Test
Python Unit TestDavid Xie
 
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-2Katy Slemon
 
Unit Testing using PHPUnit
Unit Testing using  PHPUnitUnit Testing using  PHPUnit
Unit Testing using PHPUnitvaruntaliyan
 
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)Danny Preussler
 
PHPUnit best practices presentation
PHPUnit best practices presentationPHPUnit best practices presentation
PHPUnit best practices presentationThanh Robi
 
Beginning PHPUnit
Beginning PHPUnitBeginning PHPUnit
Beginning PHPUnitJace Ju
 
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 1Kirill Rozov
 

What's hot (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
 

Viewers also liked

Tns au colloque communication verte
Tns au colloque communication verteTns au colloque communication verte
Tns au colloque communication vertecatherineguillaume
 
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
 
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 kronencatherineguillaume
 
ijoms published, Research Gate
ijoms  published, Research Gateijoms  published, Research Gate
ijoms published, Research GateSyed Muhammad Ali
 
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 Degrémont
 
Saffola Chinese Masala Oats Case Study
Saffola Chinese Masala Oats Case StudySaffola Chinese Masala Oats Case Study
Saffola Chinese Masala Oats Case StudyGaurav Raj Anand
 
Company Profile Jaya Plumbing
Company Profile Jaya PlumbingCompany Profile Jaya Plumbing
Company Profile Jaya PlumbingLutfi Shebubakar
 
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 LiteratureDr. Haxel Consult
 
Exposicion de la edad moderna
Exposicion de la  edad modernaExposicion de la  edad moderna
Exposicion de la edad modernaGiovanny Gamboa
 
Mandibular Angle Fractures
Mandibular Angle FracturesMandibular Angle Fractures
Mandibular Angle FracturesAhmed Adawy
 
Retrobulbar hemorrhage by Somu Venkatesh
Retrobulbar hemorrhage by Somu VenkateshRetrobulbar hemorrhage by Somu Venkatesh
Retrobulbar hemorrhage by Somu VenkateshSomu Venkatesh
 
Reconstruction of mandibular defects
Reconstruction of mandibular defectsReconstruction of mandibular defects
Reconstruction of mandibular defectsAhmed Adawy
 
A2 Level Media Studies Production Planning
A2 Level Media Studies Production PlanningA2 Level Media Studies Production Planning
A2 Level Media Studies Production PlanningGeorginaMediaStudies
 
Slack- a presentation
Slack- a presentationSlack- a presentation
Slack- a presentationPreeti Mohan
 

Viewers also liked (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
 

Similar to Dijkstra, The Humble Programmer 1972

Confitura 2012 Bad Tests, Good Tests
Confitura 2012 Bad Tests, Good TestsConfitura 2012 Bad Tests, Good Tests
Confitura 2012 Bad Tests, Good TestsTomek Kaczanowski
 
Testing with VS2010 - A Bugs Life
Testing with VS2010 - A Bugs LifeTesting with VS2010 - A Bugs Life
Testing with VS2010 - A Bugs LifePeter Gfader
 
GeeCON 2012 Bad Tests, Good Tests
GeeCON 2012 Bad Tests, Good TestsGeeCON 2012 Bad Tests, Good Tests
GeeCON 2012 Bad Tests, Good TestsTomek 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
 
Developer Test - Things to Know
Developer Test - Things to KnowDeveloper Test - Things to Know
Developer Test - Things to Knowvilniusjug
 
1 aleksandr gritsevski - attd example using
1   aleksandr gritsevski - attd example using1   aleksandr gritsevski - attd example using
1 aleksandr gritsevski - attd example usingIevgenii Katsan
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good TestsTomek Kaczanowski
 
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 GamesUnity Technologies
 
Introduction to nsubstitute
Introduction to nsubstituteIntroduction to nsubstitute
Introduction to nsubstituteSuresh Loganatha
 
Pragmatic unittestingwithj unit
Pragmatic unittestingwithj unitPragmatic unittestingwithj unit
Pragmatic unittestingwithj unitliminescence
 
How to write clean tests
How to write clean testsHow to write clean tests
How to write clean testsDanylenko Max
 
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 appsFandy Gotama
 
"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 ID
 
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 aboutDror Helper
 
Test Infected Presentation
Test Infected PresentationTest Infected Presentation
Test Infected Presentationwillmation
 

Similar to Dijkstra, The Humble Programmer 1972 (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
 
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
 
"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)
 
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
 

Recently uploaded

Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noidabntitsolutionsrishis
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....kzayra69
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 

Recently uploaded (20)

Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
Advantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your BusinessAdvantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your Business
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 

Dijkstra, The Humble Programmer 1972

  • 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); }