SlideShare ist ein Scribd-Unternehmen logo
1 von 22
Downloaden Sie, um offline zu lesen
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);
}

Weitere ähnliche Inhalte

Was ist angesagt?

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
 

Was ist angesagt? (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
 

Andere mochten auch

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
 

Andere mochten auch (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
 

Ähnlich wie Good Tests Bad Tests

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
 
"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
 
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
 
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
 

Ähnlich wie 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
 

Kürzlich hochgeladen

WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Bert Jan Schrijver
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...masabamasaba
 
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...WSO2
 
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburgmasabamasaba
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in sowetomasabamasaba
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...Jittipong Loespradit
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...SelfMade bd
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxAnnaArtyushina1
 
WSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...masabamasaba
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareJim McKeeth
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park masabamasaba
 
tonesoftg
tonesoftgtonesoftg
tonesoftglanshi9
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfonteinmasabamasaba
 
What Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationWhat Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationJuha-Pekka Tolvanen
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...chiefasafspells
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benonimasabamasaba
 

Kürzlich hochgeladen (20)

WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
 
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptx
 
WSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaS
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
What Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationWhat Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the Situation
 
Abortion Pill Prices Boksburg [(+27832195400*)] 🏥 Women's Abortion Clinic in ...
Abortion Pill Prices Boksburg [(+27832195400*)] 🏥 Women's Abortion Clinic in ...Abortion Pill Prices Boksburg [(+27832195400*)] 🏥 Women's Abortion Clinic in ...
Abortion Pill Prices Boksburg [(+27832195400*)] 🏥 Women's Abortion Clinic in ...
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
 

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