SlideShare uma empresa Scribd logo
1 de 31
Baixar para ler offline
/24@yegor256 1
Yegor Bugayenko
Object-Oriented Flavor for
JUnit Tests
/24@yegor256 2
F.I.R.S.T.:
Fast
Isolated/Independent
Repeatable
Self-validating
Thorough and Timely
— Robert Martin

Clean Code
/24@yegor256 3
There are books:
Kent Beck, Test-Driven Development by Example, 2000.
Johannes Link, Unit testing in Java, 2003.
Ted Husted and Vincent Massol, JUnit in Action, 2003.
Andy Hunt and David Thomas, Pragmatic Unit Testing in C# with NUnit, 2003.
Gerard Meszaros, XUnit Test Patterns: Refactoring Test Code, 2007.
Nat Pryce and Steve Freeman, Growing Object-Oriented Software: Guided by Tests, 2009.
Lasse Koskela, Effective Unit Testing: A Guide for Java Developers, 2013.
J. B. Rainsberger, JUnit recipes, 2014.
Sujoy Acharya, Mastering Unit Testing Using Mockito and JUnit, 2014.
/24@yegor256 4
Unit testing anti-patterns:
Happy Path Tests
Validation and Boundary
Easy Tests
The Giant
The Cuckoo
The Conjoined Twins
The Slow Poke
Anal Probe
Test It All
Line Hitter
Wait and See
The Silent Catcher
Chain Gang
The Mockery
The Free Ride
The Local Hero
Wet Floor
The Flickering Test
The Environmental Vandal
Second Class Citizens
The Secret Catcher
Logic in Tests
Code Matching
Misleading Tests
Not Asserting
Asserting on Not-Null
/24@yegor256 5
I believe that one anti-pattern

is still missing:
The algorithm
Provided we’re talking about OOP
/24@yegor256 6
xUnit test method is

basically a procedure.
/24@yegor256 7
class BookTest {
@Test
void testWorksAsExpected() {
Book book = new Book();
book.setLanguage(Locale.RUSSIAN);
book.setEncoding(“UTF-8”);
book.setTitle(“Дон Кихот”);
assertTrue(book.getURL().contains(“%D0%94%D0%BE%D0”));
}
}
1.Algorithm
2.Output
3.Assertion
/24@yegor256 8
A test method must have nothing
but a single statement:
assertThat()
Provided we’re talking about Java
/24@yegor256 9
class BookTest {
@Test
void testWorksAsExpected() {
// nothing goes here
assertThat(
new Book(“Дон Кихот”, “UTF-8”, Locale.RUSSIAN),
new HasURL(new StringContains(“%D0%94%D0%BE%D0”))
);
}
}
/24@yegor256 10
Assert that the book is similar
to a book that has a URL that
contains a string that is equal to
“%D0%94”.
assertThat(
new Book(“Дон Кихот”, “UTF-8”, Locale.RUSSIAN),
new HasURL(new StringContains(“%D0%94%”))
);
/24@yegor256 11
Hamcrest
By the way, this is the anagram for “matchers”.
/24@yegor256 12
Some of anti-patterns will just
disappear:
Happy Path Tests
Validation and Boundary
Easy Tests
The Giant
The Cuckoo
The Conjoined Twins
The Slow Poke
Anal Probe
Test It All
Line Hitter
Wait and See
The Silent Catcher
Chain Gang
The Mockery
The Free Ride
The Local Hero
Wet Floor
The Flickering Test
The Environmental Vandal
Second Class Citizens
The Secret Catcher
Logic in Tests
Code Matching
Misleading Tests
Not Asserting
Asserting on Not-Null
/24@yegor256 13
Obvious benefits:
Reduced complexity
Immutable objects
Shared “matchers”
Fake objects and no mocking
Better design (more object-oriented)
/24@yegor256
Reduced Complexity
14
void testWorksAsExpected() {
assertThat(
new Book(“Дон Кихот”, “UTF-8”, Locale.RUSSIAN),
new HasURL(new StringContains(“%D0%94%D0%BE%D0”))
);
}
No free ride
No multi asserts
No @Before/@After
/24@yegor256
Immutable Objects
15
void testWorksAsExpected() {
assertThat(
new Book(“Дон Кихот”, “UTF-8”, Locale.RUSSIAN),
new HasURL(new StringContains(“%D0%94%D0%BE%D0”))
);
}
No setters
No temporal coupling
No procedures
/24@yegor256
Shared Matchers
16
void testWorksAsExpected() {
assertThat(
new Book(“Дон Кихот”, “UTF-8”, Locale.RUSSIAN),
new HasURL(new StringContains(“%D0%94%D0%BE%D0”))
);
}
No private static methods
No duplication
Cleaner logs
/24@yegor256
No Mocking
17
void testWorksAsExpected() {
assertThat(
new Book(“Дон Кихот”, “UTF-8”, Locale.RUSSIAN),
new HasURL(new StringContains(“%D0%94%D0%BE%D0”))
);
}
No assumptions
No false positives
/24@yegor256 18
class BookTest {
@Test
void testWorksAsExpected() {
Book b = new Book(“Дон Кихот”, “UTF-8”, Locale.RUSSIAN);
Matcher m = new HasURL(new StringContains(“%D0%94%D0%BE%D0”));
assertThat(b, m);
}
}
1.Object
2.Matcher
3.Assertion
/24@yegor256 19
OpenJDK
RandomStreamTest.java
java.util.Random
for
/24@yegor256 20
@Test
public void testIntStream() {
final long seed = System.currentTimeMillis();
final Random r1 = new Random(seed);
final int[] a = new int[SIZE];
for (int i=0; i < SIZE; i++) {
a[i] = r1.nextInt();
}
final Random r2 = new Random(seed);
final int[] b = r2.ints().limit(SIZE).toArray();
assertEquals(a, b);
}
/24@yegor256 21
private static class ArrayFromRandom {
private final Random random;
ArrayFromRandom(Random r) {
this.random = r;
}
int[] toArray(int s) {
final int[] a = new int[s];
for (int i=0; i < s; i++) {
a[i] = this.random.nextInt();
}
return a;
}
}
@Test
public void testIntStream() {
final long seed = System.currentTimeMillis();
assertEquals(
new ArrayFromRandom(
new Random(seed)
).toArray(SIZE),
new Random(seed).ints().limit(SIZE).toArray()
);
}
/24@yegor256 22
@Test
public void testIntStream() {
assertEquals(
new ArrayFromRandom(
new Random(System.currentTimeMillis() as seed)
).toArray(SIZE),
new Random(seed).ints().limit(SIZE).toArray()
);
}
/24@yegor256 23
cactoos
www.cactoos.org
/24@yegor256 24
new Pipe(
new TextAsInput(“Hello, world!”),
new FileAsOutput(new File(“test.txt”))
).push();
/24@yegor256 25
@Test
public void canCopyTextToByteArray() {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
new Pipe(
new TextAsInput(“Hello, world!”),
new OutputStreamAsOutput(baos)
).push();
assertThat(
new String(baos.toByteArray()),
Matchers.containsString(“Hello”)
);
}
/24@yegor256 26
Input input = new TeeInput(
new TextAsInput(“Hello, world!”),
new FileAsOutput(new File(“test.txt”))
);
input.read();
new LengthOfInput(input).asValue();
6168af9
/24@yegor256 27
@Test
public void canCopyTextToByteArray() {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
assertThat(
new InputAsText(
new TeeInput(
new TextAsInput(“Hello, world!”),
new OutputStreamAsOutput(baos)
)
),
Matchers.allOf(
equalTo(new String(baos.toByteArray())),
containsString(“Hello”)
)
);
}
/24@yegor256 28
@Test
public void canCopyTextToByteArray() {
ByteArrayOutputStream baos;
assertThat(
new InputAsText(
new TeeInput(
new TextAsInput(“Hello, world!”),
new OutputStreamAsOutput(baos = new ByteArrayOutputStream())
)
),
Matchers.allOf(
equalTo(new String(baos.toByteArray())),
containsString(“Hello”)
)
);
}
/24@yegor256 29
@Test
public void canCopyTextToByteArray() {
assertThat(
new InputAsText(
new TeeInput(
new TextAsInput(“Hello, world!”),
new OutputStreamAsOutput(
new ByteArrayOutputStream() as baos
)
)
),
Matchers.allOf(
equalTo(new String(baos.toByteArray())),
containsString(“Hello”)
)
);
}
/30@yegor256 30
The article on the blog:
/30@yegor256 31
shop@yegor256.com

Mais conteúdo relacionado

Mais procurados

Java → kotlin: Tests Made Simple
Java → kotlin: Tests Made SimpleJava → kotlin: Tests Made Simple
Java → kotlin: Tests Made Simpleleonsabr
 
Appium TestNG Framework and Multi-Device Automation Execution
Appium TestNG Framework and Multi-Device Automation ExecutionAppium TestNG Framework and Multi-Device Automation Execution
Appium TestNG Framework and Multi-Device Automation ExecutionpCloudy
 
EVERYTHING ABOUT STATIC CODE ANALYSIS FOR A JAVA PROGRAMMER
EVERYTHING ABOUT STATIC CODE ANALYSIS FOR A JAVA PROGRAMMEREVERYTHING ABOUT STATIC CODE ANALYSIS FOR A JAVA PROGRAMMER
EVERYTHING ABOUT STATIC CODE ANALYSIS FOR A JAVA PROGRAMMERAndrey Karpov
 
Zhongl scala summary
Zhongl scala summaryZhongl scala summary
Zhongl scala summarylunfu zhong
 
ObjectBox - The new Mobile Database
ObjectBox - The new Mobile DatabaseObjectBox - The new Mobile Database
ObjectBox - The new Mobile Databasegreenrobot
 
Cassandra drivers and libraries
Cassandra drivers and librariesCassandra drivers and libraries
Cassandra drivers and librariesDuyhai Doan
 
Cassandra Drivers and Tools
Cassandra Drivers and ToolsCassandra Drivers and Tools
Cassandra Drivers and ToolsDuyhai Doan
 

Mais procurados (8)

Java → kotlin: Tests Made Simple
Java → kotlin: Tests Made SimpleJava → kotlin: Tests Made Simple
Java → kotlin: Tests Made Simple
 
Appium TestNG Framework and Multi-Device Automation Execution
Appium TestNG Framework and Multi-Device Automation ExecutionAppium TestNG Framework and Multi-Device Automation Execution
Appium TestNG Framework and Multi-Device Automation Execution
 
EVERYTHING ABOUT STATIC CODE ANALYSIS FOR A JAVA PROGRAMMER
EVERYTHING ABOUT STATIC CODE ANALYSIS FOR A JAVA PROGRAMMEREVERYTHING ABOUT STATIC CODE ANALYSIS FOR A JAVA PROGRAMMER
EVERYTHING ABOUT STATIC CODE ANALYSIS FOR A JAVA PROGRAMMER
 
Java Programming - 04 object oriented in java
Java Programming - 04 object oriented in javaJava Programming - 04 object oriented in java
Java Programming - 04 object oriented in java
 
Zhongl scala summary
Zhongl scala summaryZhongl scala summary
Zhongl scala summary
 
ObjectBox - The new Mobile Database
ObjectBox - The new Mobile DatabaseObjectBox - The new Mobile Database
ObjectBox - The new Mobile Database
 
Cassandra drivers and libraries
Cassandra drivers and librariesCassandra drivers and libraries
Cassandra drivers and libraries
 
Cassandra Drivers and Tools
Cassandra Drivers and ToolsCassandra Drivers and Tools
Cassandra Drivers and Tools
 

Semelhante a Object-Oriented Flavor for JUnit Tests

GTAC 2014: What lurks in test suites?
GTAC 2014: What lurks in test suites?GTAC 2014: What lurks in test suites?
GTAC 2014: What lurks in test suites?Patrick Lam
 
CS5393-Korat_Mittal_Akshay_ProjReport
CS5393-Korat_Mittal_Akshay_ProjReportCS5393-Korat_Mittal_Akshay_ProjReport
CS5393-Korat_Mittal_Akshay_ProjReportAkshay Mittal
 
Not your father's tests
Not your father's testsNot your father's tests
Not your father's testsSean P. Floyd
 
Introduction to Julia
Introduction to JuliaIntroduction to Julia
Introduction to Julia岳華 杜
 
Shift-Left Testing: QA in a DevOps World by David Laulusa
Shift-Left Testing: QA in a DevOps World by David LaulusaShift-Left Testing: QA in a DevOps World by David Laulusa
Shift-Left Testing: QA in a DevOps World by David LaulusaQA or the Highway
 
Advances in Unit Testing: Theory and Practice
Advances in Unit Testing: Theory and PracticeAdvances in Unit Testing: Theory and Practice
Advances in Unit Testing: Theory and PracticeTao Xie
 
Mutation Testing: Testing your tests
Mutation Testing: Testing your testsMutation Testing: Testing your tests
Mutation Testing: Testing your testsStephen Leigh
 
Immutability, and how to do it in JavaScripts
Immutability, and how to do it in JavaScriptsImmutability, and how to do it in JavaScripts
Immutability, and how to do it in JavaScriptsAnton Astashov
 
JS Lab`16. Сергей Селецкий: "Ретроспектива тестирования JavaScript"
JS Lab`16. Сергей Селецкий: "Ретроспектива тестирования JavaScript"JS Lab`16. Сергей Селецкий: "Ретроспектива тестирования JavaScript"
JS Lab`16. Сергей Селецкий: "Ретроспектива тестирования JavaScript"GeeksLab Odessa
 
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdfLECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdfShashikantSathe3
 
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arraysUnit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arraysDevaKumari Vijay
 
DLint: dynamically checking bad coding practices in JavaScript (ISSTA'15 Slides)
DLint: dynamically checking bad coding practices in JavaScript (ISSTA'15 Slides)DLint: dynamically checking bad coding practices in JavaScript (ISSTA'15 Slides)
DLint: dynamically checking bad coding practices in JavaScript (ISSTA'15 Slides)Liang Gong
 
Nighthawk: A Two-Level Genetic-Random Unit Test Data Generator
Nighthawk: A Two-Level Genetic-Random Unit Test Data GeneratorNighthawk: A Two-Level Genetic-Random Unit Test Data Generator
Nighthawk: A Two-Level Genetic-Random Unit Test Data GeneratorCS, NcState
 
Finding bugs that matter with Findbugs
Finding bugs that matter with FindbugsFinding bugs that matter with Findbugs
Finding bugs that matter with FindbugsCarol McDonald
 
Dont do it in android test automation
Dont do it in android test automationDont do it in android test automation
Dont do it in android test automationALEKSEITIURIN
 

Semelhante a Object-Oriented Flavor for JUnit Tests (20)

GTAC 2014: What lurks in test suites?
GTAC 2014: What lurks in test suites?GTAC 2014: What lurks in test suites?
GTAC 2014: What lurks in test suites?
 
CS5393-Korat_Mittal_Akshay_ProjReport
CS5393-Korat_Mittal_Akshay_ProjReportCS5393-Korat_Mittal_Akshay_ProjReport
CS5393-Korat_Mittal_Akshay_ProjReport
 
Not your father's tests
Not your father's testsNot your father's tests
Not your father's tests
 
Pattern Matching in Java 14
Pattern Matching in Java 14Pattern Matching in Java 14
Pattern Matching in Java 14
 
Introduction to Julia
Introduction to JuliaIntroduction to Julia
Introduction to Julia
 
IPA Fall Days 2019
 IPA Fall Days 2019 IPA Fall Days 2019
IPA Fall Days 2019
 
Shift-Left Testing: QA in a DevOps World by David Laulusa
Shift-Left Testing: QA in a DevOps World by David LaulusaShift-Left Testing: QA in a DevOps World by David Laulusa
Shift-Left Testing: QA in a DevOps World by David Laulusa
 
Good Practices On Test Automation
Good Practices On Test AutomationGood Practices On Test Automation
Good Practices On Test Automation
 
Advances in Unit Testing: Theory and Practice
Advances in Unit Testing: Theory and PracticeAdvances in Unit Testing: Theory and Practice
Advances in Unit Testing: Theory and Practice
 
Mutation Testing: Testing your tests
Mutation Testing: Testing your testsMutation Testing: Testing your tests
Mutation Testing: Testing your tests
 
Immutability, and how to do it in JavaScripts
Immutability, and how to do it in JavaScriptsImmutability, and how to do it in JavaScripts
Immutability, and how to do it in JavaScripts
 
JS Lab`16. Сергей Селецкий: "Ретроспектива тестирования JavaScript"
JS Lab`16. Сергей Селецкий: "Ретроспектива тестирования JavaScript"JS Lab`16. Сергей Селецкий: "Ретроспектива тестирования JavaScript"
JS Lab`16. Сергей Селецкий: "Ретроспектива тестирования JavaScript"
 
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdfLECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
 
Unit testing - A&BP CC
Unit testing - A&BP CCUnit testing - A&BP CC
Unit testing - A&BP CC
 
JUnit Pioneer
JUnit PioneerJUnit Pioneer
JUnit Pioneer
 
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arraysUnit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
 
DLint: dynamically checking bad coding practices in JavaScript (ISSTA'15 Slides)
DLint: dynamically checking bad coding practices in JavaScript (ISSTA'15 Slides)DLint: dynamically checking bad coding practices in JavaScript (ISSTA'15 Slides)
DLint: dynamically checking bad coding practices in JavaScript (ISSTA'15 Slides)
 
Nighthawk: A Two-Level Genetic-Random Unit Test Data Generator
Nighthawk: A Two-Level Genetic-Random Unit Test Data GeneratorNighthawk: A Two-Level Genetic-Random Unit Test Data Generator
Nighthawk: A Two-Level Genetic-Random Unit Test Data Generator
 
Finding bugs that matter with Findbugs
Finding bugs that matter with FindbugsFinding bugs that matter with Findbugs
Finding bugs that matter with Findbugs
 
Dont do it in android test automation
Dont do it in android test automationDont do it in android test automation
Dont do it in android test automation
 

Mais de Yegor Bugayenko

Can Distributed Teams Deliver Quality?
Can Distributed Teams Deliver Quality?Can Distributed Teams Deliver Quality?
Can Distributed Teams Deliver Quality?Yegor Bugayenko
 
Are You Sure You Are Not a Micromanager?
Are You Sure You Are Not a Micromanager?Are You Sure You Are Not a Micromanager?
Are You Sure You Are Not a Micromanager?Yegor Bugayenko
 
On Requirements Management (Demotivate Them Right)
On Requirements Management (Demotivate Them Right)On Requirements Management (Demotivate Them Right)
On Requirements Management (Demotivate Them Right)Yegor Bugayenko
 
My Experience of 1000 Interviews
My Experience of 1000 InterviewsMy Experience of 1000 Interviews
My Experience of 1000 InterviewsYegor Bugayenko
 
Are you sure you are not a micromanager?
Are you sure you are not a micromanager?Are you sure you are not a micromanager?
Are you sure you are not a micromanager?Yegor Bugayenko
 
Quality Assurance vs. Testing
Quality Assurance vs. TestingQuality Assurance vs. Testing
Quality Assurance vs. TestingYegor Bugayenko
 
Typical Pitfalls in Testing
Typical Pitfalls in TestingTypical Pitfalls in Testing
Typical Pitfalls in TestingYegor Bugayenko
 
Software Testing Pitfalls
Software Testing PitfallsSoftware Testing Pitfalls
Software Testing PitfallsYegor Bugayenko
 
Five Trends We Are Afraid Of
Five Trends We Are Afraid OfFive Trends We Are Afraid Of
Five Trends We Are Afraid OfYegor Bugayenko
 
Who Cares About Quality?
Who Cares About Quality?Who Cares About Quality?
Who Cares About Quality?Yegor Bugayenko
 
Zold: a cryptocurrency without Blockchain
Zold: a cryptocurrency without BlockchainZold: a cryptocurrency without Blockchain
Zold: a cryptocurrency without BlockchainYegor Bugayenko
 
How to Cut Corners and Stay Cool
How to Cut Corners and Stay CoolHow to Cut Corners and Stay Cool
How to Cut Corners and Stay CoolYegor Bugayenko
 
Java Annotations Are a Bad Idea
Java Annotations Are a Bad IdeaJava Annotations Are a Bad Idea
Java Annotations Are a Bad IdeaYegor Bugayenko
 

Mais de Yegor Bugayenko (20)

Can Distributed Teams Deliver Quality?
Can Distributed Teams Deliver Quality?Can Distributed Teams Deliver Quality?
Can Distributed Teams Deliver Quality?
 
Are You Sure You Are Not a Micromanager?
Are You Sure You Are Not a Micromanager?Are You Sure You Are Not a Micromanager?
Are You Sure You Are Not a Micromanager?
 
On Requirements Management (Demotivate Them Right)
On Requirements Management (Demotivate Them Right)On Requirements Management (Demotivate Them Right)
On Requirements Management (Demotivate Them Right)
 
My Experience of 1000 Interviews
My Experience of 1000 InterviewsMy Experience of 1000 Interviews
My Experience of 1000 Interviews
 
Are you sure you are not a micromanager?
Are you sure you are not a micromanager?Are you sure you are not a micromanager?
Are you sure you are not a micromanager?
 
Quality Assurance vs. Testing
Quality Assurance vs. TestingQuality Assurance vs. Testing
Quality Assurance vs. Testing
 
Is Java Getting Better?
Is Java Getting Better?Is Java Getting Better?
Is Java Getting Better?
 
Typical Pitfalls in Testing
Typical Pitfalls in TestingTypical Pitfalls in Testing
Typical Pitfalls in Testing
 
Software Testing Pitfalls
Software Testing PitfallsSoftware Testing Pitfalls
Software Testing Pitfalls
 
Five Trends We Are Afraid Of
Five Trends We Are Afraid OfFive Trends We Are Afraid Of
Five Trends We Are Afraid Of
 
Experts vs Expertise
Experts vs ExpertiseExperts vs Expertise
Experts vs Expertise
 
Who Cares About Quality?
Who Cares About Quality?Who Cares About Quality?
Who Cares About Quality?
 
Quantity vs. Quality
Quantity vs. QualityQuantity vs. Quality
Quantity vs. Quality
 
Experts vs Expertise
Experts vs ExpertiseExperts vs Expertise
Experts vs Expertise
 
Zold: a cryptocurrency without Blockchain
Zold: a cryptocurrency without BlockchainZold: a cryptocurrency without Blockchain
Zold: a cryptocurrency without Blockchain
 
Life Without Blockchain
Life Without BlockchainLife Without Blockchain
Life Without Blockchain
 
How to Cut Corners and Stay Cool
How to Cut Corners and Stay CoolHow to Cut Corners and Stay Cool
How to Cut Corners and Stay Cool
 
Math or Love?
Math or Love?Math or Love?
Math or Love?
 
How much do you cost?
How much do you cost?How much do you cost?
How much do you cost?
 
Java Annotations Are a Bad Idea
Java Annotations Are a Bad IdeaJava Annotations Are a Bad Idea
Java Annotations Are a Bad Idea
 

Último

Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 

Último (20)

Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 

Object-Oriented Flavor for JUnit Tests

  • 3. /24@yegor256 3 There are books: Kent Beck, Test-Driven Development by Example, 2000. Johannes Link, Unit testing in Java, 2003. Ted Husted and Vincent Massol, JUnit in Action, 2003. Andy Hunt and David Thomas, Pragmatic Unit Testing in C# with NUnit, 2003. Gerard Meszaros, XUnit Test Patterns: Refactoring Test Code, 2007. Nat Pryce and Steve Freeman, Growing Object-Oriented Software: Guided by Tests, 2009. Lasse Koskela, Effective Unit Testing: A Guide for Java Developers, 2013. J. B. Rainsberger, JUnit recipes, 2014. Sujoy Acharya, Mastering Unit Testing Using Mockito and JUnit, 2014.
  • 4. /24@yegor256 4 Unit testing anti-patterns: Happy Path Tests Validation and Boundary Easy Tests The Giant The Cuckoo The Conjoined Twins The Slow Poke Anal Probe Test It All Line Hitter Wait and See The Silent Catcher Chain Gang The Mockery The Free Ride The Local Hero Wet Floor The Flickering Test The Environmental Vandal Second Class Citizens The Secret Catcher Logic in Tests Code Matching Misleading Tests Not Asserting Asserting on Not-Null
  • 5. /24@yegor256 5 I believe that one anti-pattern
 is still missing: The algorithm Provided we’re talking about OOP
  • 6. /24@yegor256 6 xUnit test method is
 basically a procedure.
  • 7. /24@yegor256 7 class BookTest { @Test void testWorksAsExpected() { Book book = new Book(); book.setLanguage(Locale.RUSSIAN); book.setEncoding(“UTF-8”); book.setTitle(“Дон Кихот”); assertTrue(book.getURL().contains(“%D0%94%D0%BE%D0”)); } } 1.Algorithm 2.Output 3.Assertion
  • 8. /24@yegor256 8 A test method must have nothing but a single statement: assertThat() Provided we’re talking about Java
  • 9. /24@yegor256 9 class BookTest { @Test void testWorksAsExpected() { // nothing goes here assertThat( new Book(“Дон Кихот”, “UTF-8”, Locale.RUSSIAN), new HasURL(new StringContains(“%D0%94%D0%BE%D0”)) ); } }
  • 10. /24@yegor256 10 Assert that the book is similar to a book that has a URL that contains a string that is equal to “%D0%94”. assertThat( new Book(“Дон Кихот”, “UTF-8”, Locale.RUSSIAN), new HasURL(new StringContains(“%D0%94%”)) );
  • 11. /24@yegor256 11 Hamcrest By the way, this is the anagram for “matchers”.
  • 12. /24@yegor256 12 Some of anti-patterns will just disappear: Happy Path Tests Validation and Boundary Easy Tests The Giant The Cuckoo The Conjoined Twins The Slow Poke Anal Probe Test It All Line Hitter Wait and See The Silent Catcher Chain Gang The Mockery The Free Ride The Local Hero Wet Floor The Flickering Test The Environmental Vandal Second Class Citizens The Secret Catcher Logic in Tests Code Matching Misleading Tests Not Asserting Asserting on Not-Null
  • 13. /24@yegor256 13 Obvious benefits: Reduced complexity Immutable objects Shared “matchers” Fake objects and no mocking Better design (more object-oriented)
  • 14. /24@yegor256 Reduced Complexity 14 void testWorksAsExpected() { assertThat( new Book(“Дон Кихот”, “UTF-8”, Locale.RUSSIAN), new HasURL(new StringContains(“%D0%94%D0%BE%D0”)) ); } No free ride No multi asserts No @Before/@After
  • 15. /24@yegor256 Immutable Objects 15 void testWorksAsExpected() { assertThat( new Book(“Дон Кихот”, “UTF-8”, Locale.RUSSIAN), new HasURL(new StringContains(“%D0%94%D0%BE%D0”)) ); } No setters No temporal coupling No procedures
  • 16. /24@yegor256 Shared Matchers 16 void testWorksAsExpected() { assertThat( new Book(“Дон Кихот”, “UTF-8”, Locale.RUSSIAN), new HasURL(new StringContains(“%D0%94%D0%BE%D0”)) ); } No private static methods No duplication Cleaner logs
  • 17. /24@yegor256 No Mocking 17 void testWorksAsExpected() { assertThat( new Book(“Дон Кихот”, “UTF-8”, Locale.RUSSIAN), new HasURL(new StringContains(“%D0%94%D0%BE%D0”)) ); } No assumptions No false positives
  • 18. /24@yegor256 18 class BookTest { @Test void testWorksAsExpected() { Book b = new Book(“Дон Кихот”, “UTF-8”, Locale.RUSSIAN); Matcher m = new HasURL(new StringContains(“%D0%94%D0%BE%D0”)); assertThat(b, m); } } 1.Object 2.Matcher 3.Assertion
  • 20. /24@yegor256 20 @Test public void testIntStream() { final long seed = System.currentTimeMillis(); final Random r1 = new Random(seed); final int[] a = new int[SIZE]; for (int i=0; i < SIZE; i++) { a[i] = r1.nextInt(); } final Random r2 = new Random(seed); final int[] b = r2.ints().limit(SIZE).toArray(); assertEquals(a, b); }
  • 21. /24@yegor256 21 private static class ArrayFromRandom { private final Random random; ArrayFromRandom(Random r) { this.random = r; } int[] toArray(int s) { final int[] a = new int[s]; for (int i=0; i < s; i++) { a[i] = this.random.nextInt(); } return a; } } @Test public void testIntStream() { final long seed = System.currentTimeMillis(); assertEquals( new ArrayFromRandom( new Random(seed) ).toArray(SIZE), new Random(seed).ints().limit(SIZE).toArray() ); }
  • 22. /24@yegor256 22 @Test public void testIntStream() { assertEquals( new ArrayFromRandom( new Random(System.currentTimeMillis() as seed) ).toArray(SIZE), new Random(seed).ints().limit(SIZE).toArray() ); }
  • 24. /24@yegor256 24 new Pipe( new TextAsInput(“Hello, world!”), new FileAsOutput(new File(“test.txt”)) ).push();
  • 25. /24@yegor256 25 @Test public void canCopyTextToByteArray() { ByteArrayOutputStream baos = new ByteArrayOutputStream(); new Pipe( new TextAsInput(“Hello, world!”), new OutputStreamAsOutput(baos) ).push(); assertThat( new String(baos.toByteArray()), Matchers.containsString(“Hello”) ); }
  • 26. /24@yegor256 26 Input input = new TeeInput( new TextAsInput(“Hello, world!”), new FileAsOutput(new File(“test.txt”)) ); input.read(); new LengthOfInput(input).asValue(); 6168af9
  • 27. /24@yegor256 27 @Test public void canCopyTextToByteArray() { ByteArrayOutputStream baos = new ByteArrayOutputStream(); assertThat( new InputAsText( new TeeInput( new TextAsInput(“Hello, world!”), new OutputStreamAsOutput(baos) ) ), Matchers.allOf( equalTo(new String(baos.toByteArray())), containsString(“Hello”) ) ); }
  • 28. /24@yegor256 28 @Test public void canCopyTextToByteArray() { ByteArrayOutputStream baos; assertThat( new InputAsText( new TeeInput( new TextAsInput(“Hello, world!”), new OutputStreamAsOutput(baos = new ByteArrayOutputStream()) ) ), Matchers.allOf( equalTo(new String(baos.toByteArray())), containsString(“Hello”) ) ); }
  • 29. /24@yegor256 29 @Test public void canCopyTextToByteArray() { assertThat( new InputAsText( new TeeInput( new TextAsInput(“Hello, world!”), new OutputStreamAsOutput( new ByteArrayOutputStream() as baos ) ) ), Matchers.allOf( equalTo(new String(baos.toByteArray())), containsString(“Hello”) ) ); }