SlideShare a Scribd company logo
1 of 35
A quick guide to
Clean Tests
Noam Almog
Tech Lead
noam-almog
github.com/noam-almog
@NoamSon
noama@wix.com
“If you let the tests rot, then
your code will rot too”
Robert C. Martin
01 / Guidelines
● Readability, Readability, Readability !!!
● Maintainability
● Trustworthy
Tests Guidelines
● Can it stand on it’s own ?
● Does is describe What and not How ?
● Does it express my intent ?
What is clean ?
02 / Test Structure
public void testCancel_notDoneInterrupt() throws Exception {
Future<?> future = newFutureInstance();
assertTrue(future.cancel(true));
assertTrue(future.isCancelled());
assertTrue(future.isDone());
try {
future.get();
fail("Expected CancellationException");
} catch (CancellationException e) {
assertNotNull(e.getCause());
}
}
Given
When
Then
● Init context
● Test Description
● Given - Setup test environment
● When - execute code
● Then - match expectations
Test Structure
03 / Test Description
describe("Color Code Converter", function() {
describe("RGB to Hex conversion", function() {
it("converts the basic colors", function() {
….
});
});
@Test
void succeedingTest() {
...
}
"AppPublishRequestService" should {
"return publish request if request matcher publish request id" in new ctx {
...
}
Description
JavaScript - Mocha
Java - JUnit
Scala - Specs2
● Use Neutral Language - English
Description
it("Given animal with black color will fail validation", function() {
…
});
“Given animal with black color will fail validation” in new ctx { ... }
● Java Hint: camel case is less readable
Description
void givenAnimalWithBlackColorWillFailValidation()
void Given_animal_with_black_color_will_fail_validation()
● Notice: It Does NOT compile !!!
Description
“Given animal with black color will fail validation” in new ctx {
validate(animal.copy(color = “Black”)) must beValid
}
04 / Given
● Describe What and not How
Given
cachePolicyAnnotationExtractor.cachePolicyFrom(method) returns None
def givenExtractorWithoutAnnotationFor(method: Method) { }
● Reduce number of moving parts
Given
givenDaoWith(Seq(user1, user2, user3))
givenDaoWith(user1, user2, user3) // varargs
givenDaoWith(Some(name), description)
givenDaoWith(name, description) // useless wrappers
● Don’t use concrete values if you don’t have to
Given
def givenUserWith("some@one.com", forUserId = 500) { ... }
def givenUserWith(email, forUserId = userId) { ... }
● Introduce only needed data
Given
def givenSiteWith(url, name, andDescription = description, forSiteId = siteId)
siteChecker.siteFor(siteId).name must_=== name
Given
def givenPublishDaoWith(appPublishStatus.copy(landingPageUrl = None), appInstanceId)
def givenLandingPageServiceWith(landingPageUrl, forAppInstanceId = appInstanceId)
def givenDaoContainsPublishStatusWithoutLandingPageUrlFor(appInstanceId)
def givenLandingPageServiceWith(landingPageUrl, forAppInstanceId = appInstanceId)
● One api does not serve all
givenAppStateRouterWith(CreateStandalone, forAppInstanceId = appInstanceId)
givenMetaSiteWith2(webSiteUrl, forAppInstanceId = appInstanceId)
givenAppModelServiceWith(builderModel, forAppInstanceId = appInstanceId)
givenStandaloneRenderingServiceWith(screenshots, androidCoverName,
appPublishInformation.copy(icon = pmIconUrl), withBuilderModel = builderModel,
andAppInstanceId = appInstanceId, appModelVersion)
givenBuilderServiceWith(appPublishInformation, iconUrl = pmIconUrl,
forAppInstanceId = appInstanceId)
givenPublishedStatusServiceForNewStandaloneAppFor(appInstanceId)
Given - Pitfall Examples
05 / When
● Do NOT hide !
When
WixBiRecordingStudio.record {
logEvent() ←-- WHEN
} andThenPlay { recording =>
recording.play must contain(exactly(
aBiEventWithEntries("bar" -> "baz", "method" -> "foo")))
}
06 / Then
● Do NOT assert against anything you didn’t
define
Then
WixBiRecordingStudio.record {
logEvent()
} andThenPlay { recording =>
recording.play must contain(exactly(
aBiEventWithEntries("bar" -> "baz", "method" -> "foo")))
}
● Describe what you are matching and not how
Then
person.age must be_>=(13)
person.age must be_<=(18)
person.location must_=== "USA"
person must beAmericanTeenager
● Error message are important
Then
07 / Initialize Context
● Notice: Not visible for test reader
● Define only initialization code, cleanup etc.
● Hide only irrelevant logic
Context Initialization
08 / Demo
"given no annotation return default cache headers" in new ctx {
cachePolicyAnnotationExtractor.cachePolicyFrom(method) returns None
cachePolicyManager.cachePolicyHeadersFor(method) must
containTheSameElementsAs(Seq("Cache-Control" -> "no-cache",
"Pragma" -> "no-cache"))
}
Demo - Before
"given no annotation return default cache headers" in new ctx {
givenExtractorWithoutCachePolicyFor(method)
cachePolicyManager.cachePolicyHeadersFor(method) must
containTheSameElementsAs(Seq("Cache-Control" -> "no-cache",
"Pragma" -> "no-cache"))
}
Demo - After 1
"given no annotation return default cache headers" in new ctx {
givenExtractorWithoutCachePolicyFor(method)
cachePolicyManager.cachePolicyHeadersFor(method) must
haveNoCacheControlHeaders
}
Demo - After 2
09 / Conclusion
● Test should stand on it’s own
● Reduce number of moving parts
● Don’t use anything you didn’t define
● Don’t define anything you won’t use
● Describe What and not How
● Use Neutral Language - English
Conclusion
This is where you are going to present your final words.
This slide is not meant to have a lot of text.Thank You!
Any Questions?
Noam Almog
noam-almog github.com/noam-
almog
@NoamSonnoama@wix.com

More Related Content

What's hot

Thomas braun dependency-injection_with_robo_guice-presentation-final
Thomas braun dependency-injection_with_robo_guice-presentation-finalThomas braun dependency-injection_with_robo_guice-presentation-final
Thomas braun dependency-injection_with_robo_guice-presentation-finalDroidcon Berlin
 
Developer Test - Things to Know
Developer Test - Things to KnowDeveloper Test - Things to Know
Developer Test - Things to Knowvilniusjug
 
Isomorphic React Apps Testing
Isomorphic React Apps TestingIsomorphic React Apps Testing
Isomorphic React Apps TestingMikhail Larchanka
 
Beautiful java script
Beautiful java scriptBeautiful java script
Beautiful java scriptÜrgo Ringo
 
Practical JavaScript Programming - Session 4/8
Practical JavaScript Programming - Session 4/8Practical JavaScript Programming - Session 4/8
Practical JavaScript Programming - Session 4/8Wilson Su
 
Secret unit testing tools no one ever told you about
Secret unit testing tools no one ever told you aboutSecret unit testing tools no one ever told you about
Secret unit testing tools no one ever told you aboutDror Helper
 
Construire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleConstruire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleThierry Wasylczenko
 
Unit Testing Front End JavaScript
Unit Testing Front End JavaScriptUnit Testing Front End JavaScript
Unit Testing Front End JavaScriptFITC
 
Java Bytecode: Passing Parameters
Java Bytecode: Passing ParametersJava Bytecode: Passing Parameters
Java Bytecode: Passing ParametersAnton Arhipov
 
Redux Thunk - Fu - Fighting with Async
Redux Thunk - Fu - Fighting with AsyncRedux Thunk - Fu - Fighting with Async
Redux Thunk - Fu - Fighting with AsyncArtur Szott
 
2. Design patterns. part #2
2. Design patterns. part #22. Design patterns. part #2
2. Design patterns. part #2Leonid Maslov
 
VISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEVISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEDarwin Durand
 

What's hot (20)

Thomas braun dependency-injection_with_robo_guice-presentation-final
Thomas braun dependency-injection_with_robo_guice-presentation-finalThomas braun dependency-injection_with_robo_guice-presentation-final
Thomas braun dependency-injection_with_robo_guice-presentation-final
 
Deep dive into Oracle ADF
Deep dive into Oracle ADFDeep dive into Oracle ADF
Deep dive into Oracle ADF
 
Developer Test - Things to Know
Developer Test - Things to KnowDeveloper Test - Things to Know
Developer Test - Things to Know
 
Isomorphic React Apps Testing
Isomorphic React Apps TestingIsomorphic React Apps Testing
Isomorphic React Apps Testing
 
Beautiful java script
Beautiful java scriptBeautiful java script
Beautiful java script
 
Con5623 pdf 5623_001
Con5623 pdf 5623_001Con5623 pdf 5623_001
Con5623 pdf 5623_001
 
Practical JavaScript Programming - Session 4/8
Practical JavaScript Programming - Session 4/8Practical JavaScript Programming - Session 4/8
Practical JavaScript Programming - Session 4/8
 
Good Tests Bad Tests
Good Tests Bad TestsGood Tests Bad Tests
Good Tests Bad Tests
 
Secret unit testing tools no one ever told you about
Secret unit testing tools no one ever told you aboutSecret unit testing tools no one ever told you about
Secret unit testing tools no one ever told you about
 
#JavaFX.forReal() - ElsassJUG
#JavaFX.forReal() - ElsassJUG#JavaFX.forReal() - ElsassJUG
#JavaFX.forReal() - ElsassJUG
 
Construire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleConstruire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradle
 
Hidden rocks in Oracle ADF
Hidden rocks in Oracle ADFHidden rocks in Oracle ADF
Hidden rocks in Oracle ADF
 
Unit Testing Front End JavaScript
Unit Testing Front End JavaScriptUnit Testing Front End JavaScript
Unit Testing Front End JavaScript
 
iOS Testing
iOS TestingiOS Testing
iOS Testing
 
Java Bytecode: Passing Parameters
Java Bytecode: Passing ParametersJava Bytecode: Passing Parameters
Java Bytecode: Passing Parameters
 
Redux Thunk - Fu - Fighting with Async
Redux Thunk - Fu - Fighting with AsyncRedux Thunk - Fu - Fighting with Async
Redux Thunk - Fu - Fighting with Async
 
Deferred
DeferredDeferred
Deferred
 
2. Design patterns. part #2
2. Design patterns. part #22. Design patterns. part #2
2. Design patterns. part #2
 
VISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEVISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLE
 
Easy Button
Easy ButtonEasy Button
Easy Button
 

Similar to Clean Test

Android Best Practices
Android Best PracticesAndroid Best Practices
Android Best PracticesYekmer Simsek
 
Testing with VS2010 - A Bugs Life
Testing with VS2010 - A Bugs LifeTesting with VS2010 - A Bugs Life
Testing with VS2010 - A Bugs LifePeter Gfader
 
Android testing
Android testingAndroid testing
Android testingSean Tsai
 
Dev fest kyoto_2021-flutter_test
Dev fest kyoto_2021-flutter_testDev fest kyoto_2021-flutter_test
Dev fest kyoto_2021-flutter_testMasanori Kato
 
Top100summit 谷歌-scott-improve your automated web application testing
Top100summit  谷歌-scott-improve your automated web application testingTop100summit  谷歌-scott-improve your automated web application testing
Top100summit 谷歌-scott-improve your automated web application testingdrewz lin
 
2011 py con
2011 py con2011 py con
2011 py conEing Ong
 
Keep your Wicket application in production
Keep your Wicket application in productionKeep your Wicket application in production
Keep your Wicket application in productionMartijn Dashorst
 
E2E testing con nightwatch.js - Drupalcamp Spain 2018
E2E testing con nightwatch.js  - Drupalcamp Spain 2018E2E testing con nightwatch.js  - Drupalcamp Spain 2018
E2E testing con nightwatch.js - Drupalcamp Spain 2018Salvador Molina (Slv_)
 
Native Payment - Part 3.pdf
Native Payment - Part 3.pdfNative Payment - Part 3.pdf
Native Payment - Part 3.pdfShaiAlmog1
 
Android the Agile way
Android the Agile wayAndroid the Agile way
Android the Agile wayAshwin Raghav
 
Unit tests and mocks
Unit tests and mocksUnit tests and mocks
Unit tests and mocksAyla Khan
 
Developer Tests - Things to Know
Developer Tests - Things to KnowDeveloper Tests - Things to Know
Developer Tests - Things to KnowVaidas Pilkauskas
 
Javascript unit testing, yes we can e big
Javascript unit testing, yes we can   e bigJavascript unit testing, yes we can   e big
Javascript unit testing, yes we can e bigAndy Peterson
 
Describe's Full of It's
Describe's Full of It'sDescribe's Full of It's
Describe's Full of It'sJim Lynch
 
Grails unit testing
Grails unit testingGrails unit testing
Grails unit testingpleeps
 
UI-Testing - Selenium? Rich-Clients? Containers? @APEX connect 2018
UI-Testing - Selenium? Rich-Clients? Containers? @APEX connect 2018UI-Testing - Selenium? Rich-Clients? Containers? @APEX connect 2018
UI-Testing - Selenium? Rich-Clients? Containers? @APEX connect 2018Tobias Schneck
 
Mobile developer is Software developer
Mobile developer is Software developerMobile developer is Software developer
Mobile developer is Software developerEugen Martynov
 

Similar to Clean Test (20)

Android Best Practices
Android Best PracticesAndroid Best Practices
Android Best Practices
 
Testing with VS2010 - A Bugs Life
Testing with VS2010 - A Bugs LifeTesting with VS2010 - A Bugs Life
Testing with VS2010 - A Bugs Life
 
Android testing
Android testingAndroid testing
Android testing
 
Dev fest kyoto_2021-flutter_test
Dev fest kyoto_2021-flutter_testDev fest kyoto_2021-flutter_test
Dev fest kyoto_2021-flutter_test
 
Top100summit 谷歌-scott-improve your automated web application testing
Top100summit  谷歌-scott-improve your automated web application testingTop100summit  谷歌-scott-improve your automated web application testing
Top100summit 谷歌-scott-improve your automated web application testing
 
2011 py con
2011 py con2011 py con
2011 py con
 
Keep your Wicket application in production
Keep your Wicket application in productionKeep your Wicket application in production
Keep your Wicket application in production
 
E2E testing con nightwatch.js - Drupalcamp Spain 2018
E2E testing con nightwatch.js  - Drupalcamp Spain 2018E2E testing con nightwatch.js  - Drupalcamp Spain 2018
E2E testing con nightwatch.js - Drupalcamp Spain 2018
 
Native Payment - Part 3.pdf
Native Payment - Part 3.pdfNative Payment - Part 3.pdf
Native Payment - Part 3.pdf
 
Android the Agile way
Android the Agile wayAndroid the Agile way
Android the Agile way
 
Unit tests and mocks
Unit tests and mocksUnit tests and mocks
Unit tests and mocks
 
Angular testing
Angular testingAngular testing
Angular testing
 
Developer Tests - Things to Know
Developer Tests - Things to KnowDeveloper Tests - Things to Know
Developer Tests - Things to Know
 
Javascript unit testing, yes we can e big
Javascript unit testing, yes we can   e bigJavascript unit testing, yes we can   e big
Javascript unit testing, yes we can e big
 
Describe's Full of It's
Describe's Full of It'sDescribe's Full of It's
Describe's Full of It's
 
Grails unit testing
Grails unit testingGrails unit testing
Grails unit testing
 
UI-Testing - Selenium? Rich-Clients? Containers? @APEX connect 2018
UI-Testing - Selenium? Rich-Clients? Containers? @APEX connect 2018UI-Testing - Selenium? Rich-Clients? Containers? @APEX connect 2018
UI-Testing - Selenium? Rich-Clients? Containers? @APEX connect 2018
 
Full Stack Unit Testing
Full Stack Unit TestingFull Stack Unit Testing
Full Stack Unit Testing
 
Mobile developer is Software developer
Mobile developer is Software developerMobile developer is Software developer
Mobile developer is Software developer
 
Android Pro Recipes
Android Pro RecipesAndroid Pro Recipes
Android Pro Recipes
 

Recently uploaded

Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....ShaimaaMohamedGalal
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
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 ...harshavardhanraghave
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
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 ...OnePlan Solutions
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 

Recently uploaded (20)

Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
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
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
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 ...
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
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 ...
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 

Clean Test

  • 1. A quick guide to Clean Tests Noam Almog Tech Lead noam-almog github.com/noam-almog @NoamSon noama@wix.com
  • 2. “If you let the tests rot, then your code will rot too” Robert C. Martin
  • 4. ● Readability, Readability, Readability !!! ● Maintainability ● Trustworthy Tests Guidelines
  • 5. ● Can it stand on it’s own ? ● Does is describe What and not How ? ● Does it express my intent ? What is clean ?
  • 6. 02 / Test Structure
  • 7. public void testCancel_notDoneInterrupt() throws Exception { Future<?> future = newFutureInstance(); assertTrue(future.cancel(true)); assertTrue(future.isCancelled()); assertTrue(future.isDone()); try { future.get(); fail("Expected CancellationException"); } catch (CancellationException e) { assertNotNull(e.getCause()); } } Given When Then
  • 8. ● Init context ● Test Description ● Given - Setup test environment ● When - execute code ● Then - match expectations Test Structure
  • 9. 03 / Test Description
  • 10. describe("Color Code Converter", function() { describe("RGB to Hex conversion", function() { it("converts the basic colors", function() { …. }); }); @Test void succeedingTest() { ... } "AppPublishRequestService" should { "return publish request if request matcher publish request id" in new ctx { ... } Description JavaScript - Mocha Java - JUnit Scala - Specs2
  • 11. ● Use Neutral Language - English Description it("Given animal with black color will fail validation", function() { … }); “Given animal with black color will fail validation” in new ctx { ... }
  • 12. ● Java Hint: camel case is less readable Description void givenAnimalWithBlackColorWillFailValidation() void Given_animal_with_black_color_will_fail_validation()
  • 13. ● Notice: It Does NOT compile !!! Description “Given animal with black color will fail validation” in new ctx { validate(animal.copy(color = “Black”)) must beValid }
  • 15. ● Describe What and not How Given cachePolicyAnnotationExtractor.cachePolicyFrom(method) returns None def givenExtractorWithoutAnnotationFor(method: Method) { }
  • 16. ● Reduce number of moving parts Given givenDaoWith(Seq(user1, user2, user3)) givenDaoWith(user1, user2, user3) // varargs givenDaoWith(Some(name), description) givenDaoWith(name, description) // useless wrappers
  • 17. ● Don’t use concrete values if you don’t have to Given def givenUserWith("some@one.com", forUserId = 500) { ... } def givenUserWith(email, forUserId = userId) { ... }
  • 18. ● Introduce only needed data Given def givenSiteWith(url, name, andDescription = description, forSiteId = siteId) siteChecker.siteFor(siteId).name must_=== name
  • 19. Given def givenPublishDaoWith(appPublishStatus.copy(landingPageUrl = None), appInstanceId) def givenLandingPageServiceWith(landingPageUrl, forAppInstanceId = appInstanceId) def givenDaoContainsPublishStatusWithoutLandingPageUrlFor(appInstanceId) def givenLandingPageServiceWith(landingPageUrl, forAppInstanceId = appInstanceId) ● One api does not serve all
  • 20. givenAppStateRouterWith(CreateStandalone, forAppInstanceId = appInstanceId) givenMetaSiteWith2(webSiteUrl, forAppInstanceId = appInstanceId) givenAppModelServiceWith(builderModel, forAppInstanceId = appInstanceId) givenStandaloneRenderingServiceWith(screenshots, androidCoverName, appPublishInformation.copy(icon = pmIconUrl), withBuilderModel = builderModel, andAppInstanceId = appInstanceId, appModelVersion) givenBuilderServiceWith(appPublishInformation, iconUrl = pmIconUrl, forAppInstanceId = appInstanceId) givenPublishedStatusServiceForNewStandaloneAppFor(appInstanceId) Given - Pitfall Examples
  • 22. ● Do NOT hide ! When WixBiRecordingStudio.record { logEvent() ←-- WHEN } andThenPlay { recording => recording.play must contain(exactly( aBiEventWithEntries("bar" -> "baz", "method" -> "foo"))) }
  • 24. ● Do NOT assert against anything you didn’t define Then WixBiRecordingStudio.record { logEvent() } andThenPlay { recording => recording.play must contain(exactly( aBiEventWithEntries("bar" -> "baz", "method" -> "foo"))) }
  • 25. ● Describe what you are matching and not how Then person.age must be_>=(13) person.age must be_<=(18) person.location must_=== "USA" person must beAmericanTeenager
  • 26. ● Error message are important Then
  • 27. 07 / Initialize Context
  • 28. ● Notice: Not visible for test reader ● Define only initialization code, cleanup etc. ● Hide only irrelevant logic Context Initialization
  • 30. "given no annotation return default cache headers" in new ctx { cachePolicyAnnotationExtractor.cachePolicyFrom(method) returns None cachePolicyManager.cachePolicyHeadersFor(method) must containTheSameElementsAs(Seq("Cache-Control" -> "no-cache", "Pragma" -> "no-cache")) } Demo - Before
  • 31. "given no annotation return default cache headers" in new ctx { givenExtractorWithoutCachePolicyFor(method) cachePolicyManager.cachePolicyHeadersFor(method) must containTheSameElementsAs(Seq("Cache-Control" -> "no-cache", "Pragma" -> "no-cache")) } Demo - After 1
  • 32. "given no annotation return default cache headers" in new ctx { givenExtractorWithoutCachePolicyFor(method) cachePolicyManager.cachePolicyHeadersFor(method) must haveNoCacheControlHeaders } Demo - After 2
  • 34. ● Test should stand on it’s own ● Reduce number of moving parts ● Don’t use anything you didn’t define ● Don’t define anything you won’t use ● Describe What and not How ● Use Neutral Language - English Conclusion
  • 35. This is where you are going to present your final words. This slide is not meant to have a lot of text.Thank You! Any Questions? Noam Almog noam-almog github.com/noam- almog @NoamSonnoama@wix.com

Editor's Notes

  1. having dirty tests is equivalent to, if not worse than, having no tests. I’ll start with a quote from uncle bob which shows the importance of testing, cleaning code is important but cleaning the tests is even more. Usually we write a failing test, write the code, pass the test then refactor the code to be clean and nice and then we move on to the next feature. But what about the test ? We need to spend some time cleaning it up and then continue to the next feature. In this talk I will demonstrate some techniques on how to do that. Some of the slides are in scala but the principles are the same for all languages.
  2. - Readability, some people claim that it's the documentation for the system. what is a single test?, how to properly scope it to allow an outsider understand can the test standout on it's own ? - Maintainable, if for each change you need to change the test it usually implies that you have a badly written test. If you didn't change the behavior you should touch the test. Informative, if the test fails, can someone understand what went wrong ? - Trustworthy - when refactoring your tests make sure you don't break them don't be over obsessive about testing everything, test what needs to be tested.
  3. What should you ask yourself when you look at a test ? - can your test standalone by itself ? - did I use data that i didn't define in this scope ? - Am I not hiding too much - Talk about what you test and not How you test it. - is the test expressing what I want to do ? ---- The memento method, you forget what you wrote and you look at it with new eyes
  4. A well written structure is like a map to understanding the code.
  5. Arrange, Act, Assert
  6. So let's run through this one more time
  7. Describe action and result in plain words
  8. Describe action and result in plain words
  9. Describe action and result in plain words
  10. Pack to method and extract driver Understand the contract When driver is created it better describes the contract Randomize to detach test from data, mention property based testing
  11. Pack to method and extract driver Understand the contract When driver is created it better describes the contract Randomize to detach test from data, mention property based testing
  12. Don’t use variables that you won’t need later on
  13. Don’t use variables that you won’t need later on
  14. Don’t use the same api for all object, decompose object and
  15. Don’t hide what you are testing !
  16. Don’t use variables that you won’t need later on
  17. Don’t use variables that you won’t need later on
  18. Don’t use variables that you won’t need later on
  19. Don't over abstract the test !!! Before - reset mocks Before All - create the env
  20. Do you have to be a technical person to read this ?