This presentation explains parameterized tests, theory tests, and generative testing. It also explains single mode faults and double mode faults and shows how to reduce the number of test cases when there's an combinatorial explosion. Lot's of JUnit examples.
Presentation given for the SweNug user group. Based on the contents of my book "Developer Testing". Covers a variety of test related stuff: defining testability, test techniques, anti-testability constructs, duplication, test-driven development.
We aren't sure about you, but working with Java 8 made one of the speakers lose all of his hair and the other lose his sleep (or was it the jetlag?). If you still haven't reached the level of Brian Goetz in mastering lambdas and strings, this talk is for you. And if you think you have, we have some bad news for you, you should attend as well.
An overview of the inner-workings of OpenJDK - with emphasis on...
- what triggers the just-in-time compiler (JIT)
- types of speculative optimizations performed by the JIT
- aspects of the Java language & ecosystem that make ahead-of-time (AOT) compilation challenging
Software is eating the world. The rate at which we produce new software is astounding. Understanding and preventing potential issues is a growing concern.
Building software security teams is much different than building IT security teams. It requires different backgrounds and focus. Software security groups without an emphasis on software fail.
Join Aaron as he talks about the right way to build and run a software security group. You will walk away with a concrete list of actions that you can take back to your job and start working on right away.
JVM Mechanics: Understanding the JIT's TricksDoug Hawkins
In this talk, we'll walkthrough how the JIT optimizes a piece Java code step-by-step. In doing so, you'll learn some of the amazing feats of optimization that JVMs can perform, but also some surprisingly simple things that prevent your code from running fast.
This talk is a look into some of the surprising performance cases in Java -- with the goal of illustrating a few simple truths about the nature of compilers.
Presentation given for the SweNug user group. Based on the contents of my book "Developer Testing". Covers a variety of test related stuff: defining testability, test techniques, anti-testability constructs, duplication, test-driven development.
We aren't sure about you, but working with Java 8 made one of the speakers lose all of his hair and the other lose his sleep (or was it the jetlag?). If you still haven't reached the level of Brian Goetz in mastering lambdas and strings, this talk is for you. And if you think you have, we have some bad news for you, you should attend as well.
An overview of the inner-workings of OpenJDK - with emphasis on...
- what triggers the just-in-time compiler (JIT)
- types of speculative optimizations performed by the JIT
- aspects of the Java language & ecosystem that make ahead-of-time (AOT) compilation challenging
Software is eating the world. The rate at which we produce new software is astounding. Understanding and preventing potential issues is a growing concern.
Building software security teams is much different than building IT security teams. It requires different backgrounds and focus. Software security groups without an emphasis on software fail.
Join Aaron as he talks about the right way to build and run a software security group. You will walk away with a concrete list of actions that you can take back to your job and start working on right away.
JVM Mechanics: Understanding the JIT's TricksDoug Hawkins
In this talk, we'll walkthrough how the JIT optimizes a piece Java code step-by-step. In doing so, you'll learn some of the amazing feats of optimization that JVMs can perform, but also some surprisingly simple things that prevent your code from running fast.
This talk is a look into some of the surprising performance cases in Java -- with the goal of illustrating a few simple truths about the nature of compilers.
RxJava и Android. Плюсы, минусы, подводные камниStfalcon Meetups
Ярослав Герьятович
Android Engineer в компании Attendify . Спикер на UA Mobile'14 . Идеолог функционального и реактивного подхода в проектировании Android приложений.
Taking the boilerplate out of your tests with SourceryVincent Pradeilles
Code generation has always been something of a controversial topic, with many engineers not liking the idea of a codebase that relies too much on this topic. Yet, when used appropriately, this tool is a great help to minimise boilerplate code.
In many iOS projects, the testing targets are definitely places that tend to be cluttered with boilerplate and duplicated code.
Sourcery is a code-generation tool for Swift that, when applied appropriately, can dramatically reduce the amount of boilerplate.
In this talk I’m going to show you how it can be leveraged for quick win, such as making sure that your dependencies are correctly registered and injected. But also to create building blocks for more involved tests scenarios, such as mocks that keep track of how many times methods get called, along with the provided arguments. And, of course, if your app uses an architecture that relies on a set of well defined components (like base classes of ViewControllers, ViewModels, Providers, etc. with pre-defined methods), Sourcery can definitely be applied to generate a testing suite that will assert that those components behave as expected.
1. Basic Java class
class Ex1
{
public static void main(String args[])
{
int width;
int length;
int height;
width=5;
length=12;
height=3;
int v;
v=width*length*height;
System.out.println("Volume is :"+v);
}
}
Volume is :180
Spotify 2016 - Beyond Lambdas - the AftermathDaniel Sawano
This presentation was given by Daniel Deogun and Daniel Sawano at the Spotify Java Conference, Stockholm, 2016.
-----------------
As Java developers we are used to having rich ecosystems of libraries and tools that make our lives easier. As of the release of Java 8, we finally got our hands on building blocks like lambdas, optionals, and streams. All sorts of tools that help us write more concise code. But now, when the honeymoon is over, are there any downsides to Java 8 or is it a silver bullet? Are there any new anti-patterns emerging? Or subtle bugs caused by the new style of programming? Have there been any lessons learned? Are there any best practices? If you are interested in learning about the challenges encountered when moving over to a functional style of Java programming, what code constructs to avoid, and best practices to use, well then this session is for you.
A quick presentation on JAVA Puzzlers inspired by the study of Eric Lefevre-Ardant and Guillaume Tardif. A few puzzlers to understand the tricks of the language.
Example of using Kotlin lang features for writing DSL for Spark-Cassandra connector. Comparison Kotlin lang DSL features with similar features in others JVM languages (Scala, Groovy).
JDays 2016 - Beyond Lambdas - the AftermathDaniel Sawano
This presentation was given by Daniel Deogun and Daniel Sawano at the JDays conference, Gothenburg, 2016.
-----------------
As Java developers we are used to having rich ecosystems of libraries and tools that make our lives easier. As of the release of Java 8, we finally got our hands on building blocks like lambdas, optionals, and streams. All sorts of tools that help us write more concise code. But now, when the honeymoon is over, are there any downsides to Java 8 or is it a silver bullet? Are there any new anti-patterns emerging? Or subtle bugs caused by the new style of programming? Have there been any lessons learned? Are there any best practices? If you are interested in learning about the challenges encountered when moving over to a functional style of Java programming, what code constructs to avoid, and best practices to use, well then this session is for you.
Reviews examples of details on how to pass data to a stored procedure and how to return data from a stored procedure. Further shows how to pass status or debugging messages from stored procedure, including message localization.
RxJava и Android. Плюсы, минусы, подводные камниStfalcon Meetups
Ярослав Герьятович
Android Engineer в компании Attendify . Спикер на UA Mobile'14 . Идеолог функционального и реактивного подхода в проектировании Android приложений.
Taking the boilerplate out of your tests with SourceryVincent Pradeilles
Code generation has always been something of a controversial topic, with many engineers not liking the idea of a codebase that relies too much on this topic. Yet, when used appropriately, this tool is a great help to minimise boilerplate code.
In many iOS projects, the testing targets are definitely places that tend to be cluttered with boilerplate and duplicated code.
Sourcery is a code-generation tool for Swift that, when applied appropriately, can dramatically reduce the amount of boilerplate.
In this talk I’m going to show you how it can be leveraged for quick win, such as making sure that your dependencies are correctly registered and injected. But also to create building blocks for more involved tests scenarios, such as mocks that keep track of how many times methods get called, along with the provided arguments. And, of course, if your app uses an architecture that relies on a set of well defined components (like base classes of ViewControllers, ViewModels, Providers, etc. with pre-defined methods), Sourcery can definitely be applied to generate a testing suite that will assert that those components behave as expected.
1. Basic Java class
class Ex1
{
public static void main(String args[])
{
int width;
int length;
int height;
width=5;
length=12;
height=3;
int v;
v=width*length*height;
System.out.println("Volume is :"+v);
}
}
Volume is :180
Spotify 2016 - Beyond Lambdas - the AftermathDaniel Sawano
This presentation was given by Daniel Deogun and Daniel Sawano at the Spotify Java Conference, Stockholm, 2016.
-----------------
As Java developers we are used to having rich ecosystems of libraries and tools that make our lives easier. As of the release of Java 8, we finally got our hands on building blocks like lambdas, optionals, and streams. All sorts of tools that help us write more concise code. But now, when the honeymoon is over, are there any downsides to Java 8 or is it a silver bullet? Are there any new anti-patterns emerging? Or subtle bugs caused by the new style of programming? Have there been any lessons learned? Are there any best practices? If you are interested in learning about the challenges encountered when moving over to a functional style of Java programming, what code constructs to avoid, and best practices to use, well then this session is for you.
A quick presentation on JAVA Puzzlers inspired by the study of Eric Lefevre-Ardant and Guillaume Tardif. A few puzzlers to understand the tricks of the language.
Example of using Kotlin lang features for writing DSL for Spark-Cassandra connector. Comparison Kotlin lang DSL features with similar features in others JVM languages (Scala, Groovy).
JDays 2016 - Beyond Lambdas - the AftermathDaniel Sawano
This presentation was given by Daniel Deogun and Daniel Sawano at the JDays conference, Gothenburg, 2016.
-----------------
As Java developers we are used to having rich ecosystems of libraries and tools that make our lives easier. As of the release of Java 8, we finally got our hands on building blocks like lambdas, optionals, and streams. All sorts of tools that help us write more concise code. But now, when the honeymoon is over, are there any downsides to Java 8 or is it a silver bullet? Are there any new anti-patterns emerging? Or subtle bugs caused by the new style of programming? Have there been any lessons learned? Are there any best practices? If you are interested in learning about the challenges encountered when moving over to a functional style of Java programming, what code constructs to avoid, and best practices to use, well then this session is for you.
Reviews examples of details on how to pass data to a stored procedure and how to return data from a stored procedure. Further shows how to pass status or debugging messages from stored procedure, including message localization.
Video and slides synchronized, mp3 and slide download available at URL http://bit.ly/254wkpw.
Aaron Bedra focuses on describing a system as a series of models that can be used to systematically and automatically generate input data and ensure that a code is behaving as expected. Bedra discusses property based testing and how it can help one build more resilient systems and even reduce the time needed to maintain a test suite. Filmed at qconlondon.com.
Aaron Bedra is Chief Security Officer at eligible.com. He is the creator of Repsheet, an open source threat intelligence framework. Bedra is the co-author of Programming Clojure, 2nd Edition and a frequent contributor to open source software.
JUnit is the de facto standard in Java testing. Yet many advanced JUnit features are little known and poorly understood. This session reviews some lesser-known features of JUnit, along with a few associated libraries, that can make your unit tests more powerful, expressive, and fun. The session is intended for Java developers, lead developers, and architects trying to introduce good testing practices into their teams.
So you’ve developed an app in MongoDB Stitch? Now what? What is day-to-day use of MongoDB Stitch really like? We’ll talk topics like multi-environment deployment (dev → test → production); logging; testing and timing; and how to best make MongoDB and Stitch work for your application.
A presentation on JUnit Pioneer given at Fortitude Technologies on Mar. 4, 2021. JUnit Pioneer is an extension library for JUnit 5 (Jupiter).
Sample code on GitHub at:
https://github.com/sleberknight/junit-pioneering-presentation-code
JUnit Pioneer home page:
https://junit-pioneer.org
How to ship customer value faster with step functionsYan Cui
In this talk, I'm gonna tell you all about AWS Step Functions - how it works, when to use it, and some tips on how to accelerate app development so you can ship customer values faster.
Recording: coming soon
Real-world serverless podcast: https://realworldserverless.com
Learn Lambda best practices: https://lambdabestpractice.com
Blog: https://theburningmonk.com
Consulting services: https://theburningmonk.com/hire-me
Production-Ready Serverless workshop: https://productionreadyserverless.com
When you write unit tests for your projects, there’s a fair chance that you do so by following the classical « Given-When-Then » paradigm, in which you set some input data, execute the code you’re testing, and finally assert that its outcome is indeed the one you expected.
While this approach is perfectly sound, it does suffer one downside: your program will only be tested on the static input data defined in your tests, and there is no real guarantee that this data does cover all edge cases. This can be especially problematic for SDK developers, who, by definition, have a very hard time anticipating all the different situations in which their code will be used.
To improve on this issue, another approach exists, and it is called property-based testing. The idea behind it is very simple: you write your tests by defining properties that must always be true for your program. For example, « an array reversed twice is always equal to itself ». The testing framework will then generate random input values and test wether the property holds or not. And, as you can imagine, this approach is extremely good at narrowing down on overlooked edge cases.
In Swift, we are lucky enough to already have a full-fledged implementation called SwiftCheck, that enables property-based testing (https://github.com/typelift/SwiftCheck). The goal of this talk is thus to explain how property-based testing can be a powerful addition to a testing suite, and give actual and actionable examples of how it can be added to a project using SwiftCheck.
This webinar by Oleksandr Navka (Lead Software Engineer, Consultant, GlobalLogic) was delivered at Java Community Webinar #1 on August 12, 2020.
Webinar agenda:
- The new structural unit of the program is Java Records
- Updated instanceof statement
- Updated switch operator
More details and presentation: https://www.globallogic.com/ua/about/events/java-community-webinar-1/
A better version can be found at https://app.box.com/s/8zuk8yd4x9m7rbvinkb0xztz17x6xoqj
This is the slide for a presentation at Golang Melbourne meetup.
Similar to Dealing with combinatorial explosions and boring tests (20)
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Crescat
Crescat is industry-trusted event management software, built by event professionals for event professionals. Founded in 2017, we have three key products tailored for the live event industry.
Crescat Event for concert promoters and event agencies. Crescat Venue for music venues, conference centers, wedding venues, concert halls and more. And Crescat Festival for festivals, conferences and complex events.
With a wide range of popular features such as event scheduling, shift management, volunteer and crew coordination, artist booking and much more, Crescat is designed for customisation and ease-of-use.
Over 125,000 events have been planned in Crescat and with hundreds of customers of all shapes and sizes, from boutique event agencies through to international concert promoters, Crescat is rigged for success. What's more, we highly value feedback from our users and we are constantly improving our software with updates, new features and improvements.
If you plan events, run a venue or produce festivals and you're looking for ways to make your life easier, then we have a solution for you. Try our software for free or schedule a no-obligation demo with one of our product specialists today at crescat.io
Code reviews are vital for ensuring good code quality. They serve as one of our last lines of defense against bugs and subpar code reaching production.
Yet, they often turn into annoying tasks riddled with frustration, hostility, unclear feedback and lack of standards. How can we improve this crucial process?
In this session we will cover:
- The Art of Effective Code Reviews
- Streamlining the Review Process
- Elevating Reviews with Automated Tools
By the end of this presentation, you'll have the knowledge on how to organize and improve your code review proces
First Steps with Globus Compute Multi-User EndpointsGlobus
In this presentation we will share our experiences around getting started with the Globus Compute multi-user endpoint. Working with the Pharmacology group at the University of Auckland, we have previously written an application using Globus Compute that can offload computationally expensive steps in the researcher's workflows, which they wish to manage from their familiar Windows environments, onto the NeSI (New Zealand eScience Infrastructure) cluster. Some of the challenges we have encountered were that each researcher had to set up and manage their own single-user globus compute endpoint and that the workloads had varying resource requirements (CPUs, memory and wall time) between different runs. We hope that the multi-user endpoint will help to address these challenges and share an update on our progress here.
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Mind IT Systems
Healthcare providers often struggle with the complexities of chronic conditions and remote patient monitoring, as each patient requires personalized care and ongoing monitoring. Off-the-shelf solutions may not meet these diverse needs, leading to inefficiencies and gaps in care. It’s here, custom healthcare software offers a tailored solution, ensuring improved care and effectiveness.
Zoom is a comprehensive platform designed to connect individuals and teams efficiently. With its user-friendly interface and powerful features, Zoom has become a go-to solution for virtual communication and collaboration. It offers a range of tools, including virtual meetings, team chat, VoIP phone systems, online whiteboards, and AI companions, to streamline workflows and enhance productivity.
Large Language Models and the End of ProgrammingMatt Welsh
Talk by Matt Welsh at Craft Conference 2024 on the impact that Large Language Models will have on the future of software development. In this talk, I discuss the ways in which LLMs will impact the software industry, from replacing human software developers with AI, to replacing conventional software with models that perform reasoning, computation, and problem-solving.
OpenMetadata Community Meeting - 5th June 2024OpenMetadata
The OpenMetadata Community Meeting was held on June 5th, 2024. In this meeting, we discussed about the data quality capabilities that are integrated with the Incident Manager, providing a complete solution to handle your data observability needs. Watch the end-to-end demo of the data quality features.
* How to run your own data quality framework
* What is the performance impact of running data quality frameworks
* How to run the test cases in your own ETL pipelines
* How the Incident Manager is integrated
* Get notified with alerts when test cases fail
Watch the meeting recording here - https://www.youtube.com/watch?v=UbNOje0kf6E
Essentials of Automations: The Art of Triggers and Actions in FMESafe Software
In this second installment of our Essentials of Automations webinar series, we’ll explore the landscape of triggers and actions, guiding you through the nuances of authoring and adapting workspaces for seamless automations. Gain an understanding of the full spectrum of triggers and actions available in FME, empowering you to enhance your workspaces for efficient automation.
We’ll kick things off by showcasing the most commonly used event-based triggers, introducing you to various automation workflows like manual triggers, schedules, directory watchers, and more. Plus, see how these elements play out in real scenarios.
Whether you’re tweaking your current setup or building from the ground up, this session will arm you with the tools and insights needed to transform your FME usage into a powerhouse of productivity. Join us to discover effective strategies that simplify complex processes, enhancing your productivity and transforming your data management practices with FME. Let’s turn complexity into clarity and make your workspaces work wonders!
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus
As part of the DOE Integrated Research Infrastructure (IRI) program, NERSC at Lawrence Berkeley National Lab and ALCF at Argonne National Lab are working closely with General Atomics on accelerating the computing requirements of the DIII-D experiment. As part of the work the team is investigating ways to speedup the time to solution for many different parts of the DIII-D workflow including how they run jobs on HPC systems. One of these routes is looking at Globus Compute as a way to replace the current method for managing tasks and we describe a brief proof of concept showing how Globus Compute could help to schedule jobs and be a tool to connect compute at different facilities.
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisGlobus
JASMIN is the UK’s high-performance data analysis platform for environmental science, operated by STFC on behalf of the UK Natural Environment Research Council (NERC). In addition to its role in hosting the CEDA Archive (NERC’s long-term repository for climate, atmospheric science & Earth observation data in the UK), JASMIN provides a collaborative platform to a community of around 2,000 scientists in the UK and beyond, providing nearly 400 environmental science projects with working space, compute resources and tools to facilitate their work. High-performance data transfer into and out of JASMIN has always been a key feature, with many scientists bringing model outputs from supercomputers elsewhere in the UK, to analyse against observational or other model data in the CEDA Archive. A growing number of JASMIN users are now realising the benefits of using the Globus service to provide reliable and efficient data movement and other tasks in this and other contexts. Further use cases involve long-distance (intercontinental) transfers to and from JASMIN, and collecting results from a mobile atmospheric radar system, pushing data to JASMIN via a lightweight Globus deployment. We provide details of how Globus fits into our current infrastructure, our experience of the recent migration to GCSv5.4, and of our interest in developing use of the wider ecosystem of Globus services for the benefit of our user community.
GraphSummit Paris - The art of the possible with Graph TechnologyNeo4j
Sudhir Hasbe, Chief Product Officer, Neo4j
Join us as we explore breakthrough innovations enabled by interconnected data and AI. Discover firsthand how organizations use relationships in data to uncover contextual insights and solve our most pressing challenges – from optimizing supply chains, detecting fraud, and improving customer experiences to accelerating drug discoveries.
2. Developer (2000→) Java, Perl, C, C++, Groovy, C#, PHP,
Visual Basic, Assembler
Trainer – TDD, Unit testing, Clean Code, WebDriver,
Specification by Example
Developer mentor
Writer
Scrum Master
Coach in training
WhoamI?
https://www.crisp.se/konsulter/alexander-tarnowski
alexander_tar
alexander.tarnowski@crisp.se
3. ”We want our
customers to be able
to compute their car
insurance premiums
online.
Online quotes are in
our favor, since we
outprice our
competitors!”
Who is Tim?
Image: stockimages/freedigitalphotos.net
Alexander Tarnowski
4. Age Premium for males Premium for females
18-23 1.75 1.575
24-59 1.0 0.9
60+ 1.35 1.215
Business rules
Alexander Tarnowski
5. @Test
public void maleDriversAged18() {
assertEquals(1.75, new PremiumRuleEngine()
.getPremiumFactor(18, Gender.MALE), 0.0);
}
The first test
Age Premium for males Premium for females
18-23 1.75 1.575
24-59 1.0 0.9
60+ 1.35 1.215
Alexander Tarnowski
6. @Test
public void maleDriversAged23() {
assertEquals(1.75, new PremiumRuleEngine()
.getPremiumFactor(23, Gender.MALE), 0.0);
}
The second test
Age Premium for males Premium for females
18-23 1.75 1.575
24-59 1.0 0.9
60+ 1.35 1.215
Alexander Tarnowski
7. And this could go on…
Image: imagerymajestic/freedigitalphotos.net
Alexander Tarnowski
8. Silly names
Repetitive test structure
Boredom
Smells and insights
Image: Mister GC/freedigitalphotos.net
Alexander Tarnowski
9. How many equivalence classes?
How many boundary values?
Would we test drive all of them?
How many tests are needed?
0
0.5
1
1.5
2
18-23 24-59 60+
Male
Female
Alexander Tarnowski
10. @RunWith(Parameterized.class)
public class PremiumAgeIntervalsTest {
private double expectedPremiumFactor;
private int age;
private Gender gender;
public PremiumAgeIntervalsTest(double expectedPremiumFactor, int age, Gender gender) {
this.expectedPremiumFactor = expectedPremiumFactor;
this.age = age;
this.gender = gender;
}
@Parameters
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][]{
{1.75, 18, Gender.MALE}, {1.75, 23, Gender.MALE}, {1.0, 24, Gender.MALE},
{1.0, 59, Gender.MALE}, {1.35, 60, Gender.MALE}, {1.575, 18, Gender.FEMALE},
{1.575, 23, Gender.FEMALE}, {0.9, 24, Gender.FEMALE}, {0.9, 59, Gender.FEMALE},
{1.215, 60, Gender.FEMALE}}
);
}
@Test
public void verifyPremiumFactor() {
assertEquals(expectedPremiumFactor, new PremiumRuleEngine()
.getPremiumFactor(age, gender), 0.0);
}
}
Theparameterized version
Alexander Tarnowski
11. @RunWith(Parameterized.class)
public class PremiumAgeIntervalsTest {
@Parameter(value = 0)
public double expectedPremiumFactor;
@Parameter(value = 1)
public int age;
@Parameter(value = 2)
public Gender gender;
@Parameters(name = "Case {index}: Expected {0} for {1} year old {2}s")
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][]{
{1.75, 18, Gender.MALE}, {1.75, 23, Gender.MALE}, {1.0, 24, Gender.MALE},
{1.0, 59, Gender.MALE}, {1.35, 60, Gender.MALE}, {1.575, 18, Gender.FEMALE},
{1.575, 23, Gender.FEMALE}, {0.9, 24, Gender.FEMALE}, {0.9, 59, Gender.FEMALE},
{1.215, 60, Gender.FEMALE}}
);
}
@Test
public void verifyPremiumFactor() {
assertEquals(expectedPremiumFactor, new PremiumRuleEngine()
.getPremiumFactor(age, gender), 0.0);
}
}
Alternative syntax
Alexander Tarnowski
12. Focus on data
Allow comparing a set of predefined inputs with
some predefined output
Make checking simple
Turn tests with silly names into data-driven tests
Parameterized tests
Alexander Tarnowski
16. public class CalorieComparisonTest {
public static List<FastFood> foods() {
return Arrays.asList(Menu.FISH_BURGER,
Menu.GIGANTIC_BURGER_WITH_BACON, Menu.CHICKEN_SANDWICH,
Menu.HOTDOG);
}
@Test
public void hamburgersContainTheLeastAmountOfCaloriesAmongFastFoods() {
for (FastFood food : foods())
assertThat(Menu.HAMBURGER.getCalories(),
is(lessThan(food.getCalories())));
}
}
}
Proving the theory
Alexander Tarnowski
17. @RunWith(Theories.class)
public class CalorieComparisonTest {
@DataPoints
public static List<FastFood> foods() {
return Arrays.asList(Menu.FISH_BURGER,
Menu.GIGANTIC_BURGER_WITH_BACON, Menu.CHICKEN_SANDWICH,
Menu.HOTDOG);
}
@Theory
public void hamburgersContainTheLeastAmountOfCaloriesAmongFastFoods(FastFood food)
{
assertThat(Menu.HAMBURGER.getCalories(),
is(lessThan(food.getCalories())));
}
}
Atheorytest
Alexander Tarnowski
18. No fast food meal contains
less than 500 calories!
Amore interesting theory
Image: marin/freedigitalphotos.net
Alexander Tarnowski
19. @RunWith(Theories.class)
public class FastFoodMealTheoryTest {
@DataPoints
public static List<Main> mainCourses() {
return Arrays.asList(Menu.HAMBURGER, Menu.FISH_BURGER,
Menu.GIGANTIC_BURGER_WITH_BACON, Menu.CHICKEN_SANDWICH,
Menu.HOTDOG);
}
@DataPoints
public static List<SideOrder> sideOrders() {
return Arrays.asList(Menu.SMALL_FRENCH_FRIES, Menu.LARGE_FRENCH_FRIES,
Menu.APPLE_PIE, Menu.SMALL_CHOCOLATE_MILKSHAKE);
}
@DataPoints
public static List<Beverage> bevereges() {
return Arrays.asList(Menu.MEDIUM_COKE, Menu.LARGE_DIET_COKE,
Menu.MEDIUM_LATTE, Menu.LARGE_LATTE);
}
@Theory
public void noFastFoodMealContainsLessThan500calories(Main main,
SideOrder sideOrder,
Beverage beverage) {
assumeThat(beverage.isDiet(), is(false));
assertThat(main.getCalories() + sideOrder.getCalories() + beverage.getCalories(),
is(greaterThan(500)));
}
}
Alexander Tarnowski
20. Feed the test with all main courses and all side
orders and all beverages
Cartesian product: mains X side orders X
beverages
assumeThat prunes some combinations
Behind the scenes
(Hamburger, Small french fries, Medium coke)
(Hamburger, Small french fries, Large diet coke)
(Hamburger, Small french fries, Medium latte)
(Hamburger, Small french fries, Large latte)
(Hamburger, Large french fries, Medium coke)
(Hamburger, Large french fries, Large diet coke)
(Hamburger, Large french fries, Medium latte)
(Hamburger, Large french fries, Large latte)
…
Alexander Tarnowski
21. Are built around ”for all” type of reasoning
Can’t pair specific data points with specific results
Let you work with the Cartesian product of
multiple variables
Theories
Alexander Tarnowski
22. Let’s do the Caesarcipher…
A B C D E F G H I J K L M O P Q R S T U V X Y Z
S T U V X Y Z A B C D E F G H I J K L M O P Q R
CAESAR=USXKSJ
Alexander Tarnowski
23. Does it work?
… by borrowing an onlineimplementation
Alexander Tarnowski
24. For a bunch of different arbitrary strings…
... and a bunch of different offsets...
... try the following:
CaesarCipher.decode(CaesarCipher.encode(string, offset), offset)
Dream scenario
Alexander Tarnowski
25. @RunWith(Theories.class)
public class CaesarCipherTest {
@Theory
public void caesarCipherRoundTrip(@RandomString(maxLength = 128) String plainText,
@TestedOn(ints = {0, 1, 2, 10, 26, 27, 1000}) int offset) {
assertEquals(plainText, CaesarCipher.decode(CaesarCipher.encode(plainText, offset),
offset));
}
}
We can do that!
Alexander Tarnowski
26. RandomString.java:
@Retention(RetentionPolicy.RUNTIME)
@ParametersSuppliedBy(RandomStringSupplier.class)
public @interface RandomString {
int maxLength();
}
RandomStringSupplier.java:
public class RandomStringSupplier extends ParameterSupplier {
@Override
public List<PotentialAssignment> getValueSources(ParameterSignature signature)
throws Throwable {
RandomString annotation = signature.getAnnotation(RandomString.class);
int length = (int) (Math.random() * annotation.maxLength());
final String s = RandomStringUtils.randomAlphanumeric(length);
return Arrays.asList(PotentialAssignment.forValue("random string", s));
}
}
@RandomString
Alexander Tarnowski
27. RandomStringsSupplier.java:
public class RandomsStringSupplier extends ParameterSupplier {
@Override
public List<PotentialAssignment> getValueSources(ParameterSignature signature) throws
Throwable {
List<PotentialAssignment> values = new ArrayList<>();
RandomStrings annotation = signature.getAnnotation(RandomStrings.class);
Generator<String> stringGenerator
= strings(integers(1, 128, Distribution.INVERTED_NORMAL), characters());
for (int i = 0; i < annotation.count(); i++) {
values.add(PotentialAssignment.forValue("random string", stringGenerator.next()));
}
return values;
}
}
QuickCheck style
Alexander Tarnowski
28. Examples of generators
booleans()
dates(Long low, Long high, TimeUnit precision)
fixedValues(T... values)
strings(Generator<Integer> length, Generator<Character> characters)
arrays(Generator<? extends T> content, Class<T> type)
excludeValues(Generator<T> generator, T... excluded)
sortedLists(Generator<T> content, int low, int high)
net.java.quickcheck
public interface Generator<T> {
/**
* Generates the next instance.
*
* @return a newly created instance
*/
public T next();
}
Alexander Tarnowski
29. Anything goes!
May involve huge domains
Often involves inverse functions
Generative testing
Alexander Tarnowski
30. Now we can execute thousands of tests!
But what if we want the opposite?
Congratulations!
Alexander TarnowskiImage: zole4/freedigitalphotos.net
31. Back to car insurance premiums
Gender
Male
Female
Age interval
18-24
25-59
60+
Yearly mileage
0
1-1000
1001-3000
3001-6000
6001+
Safety features
None
Airbag
ABS
HIP
Multiple
Brand
Nissan
Volvo
Ferrari
Toyota
Ford
Volkswagen
Driving record
Model Driver
Average Joe
Unlucky Uma
Bad Judgement Jed
Dangerous Dan
2 x 3 x 5 x 5 x 6 x 5
= 4500
Alexander Tarnowski
32. One parameter causes the error
Only 6 tests are needed!
Single mode faults
Brand Drivingrecord Yearlymileage Safetyfeatures Ageinterval Gender
Nissan ModelDriver 0 None 18-24 Male
Volvo AverageJoe 1-1000 Airbag 25-59 Female
Ferrari UnluckyUma 1001-3000 ABS 60+ -
Toyota BadJudgementJed 3001-6000 HIP - -
Ford DangerousDan 6001+ Multiple - -
Volkswagen - - - - -
Alexander Tarnowski
33. A combination of two parameters causes the error
Run through a tool that computes all pairs (or look
up in a table of orthogonal arrays)
Only ~40 tests are needed!
Double mode faults
Alexander Tarnowski
34. Finding all pairs by hand
Row Variable 1 Variable 2 Variable 3
1 A X Q
2 A X R
3 A Y Q
4 A Y R
5 B X Q
6 B X R
7 B Y Q
8 B Y R
Alexander Tarnowski
35. Theoretical foundation: orthogonal arrays
Reduce the number of tests from thousands to
just a few
Great to put into parameterized tests
Finding Single and Doublemode faults
Alexander Tarnowski
36. Unit tests are examples
Parameterized tests make writing many similar
tests easy
Theory tests introduce general statements about
program elements
Generative tests – Anything goes!
Single mode faults & double mode faults –
Reduce the number of tests and feed
parameterized tests
Summary
Alexander Tarnowski