SlideShare a Scribd company logo
Creating Data with the Test Data
Builder Pattern
CukeUp! 2013
Alan Parkinson
Create test data with the most
appropriate tools and
using a sensible DSL
Scenario AUT
Database
Creating data with the test data builder pattern
Creating data with the test data builder pattern
Build method
Safe Defaults
Chainable
public class UserBuilder {
String name = “admin”;
String password = “admin”;
…
public User build() {
return new User(admin, password);
}
…
}
User user = new UserBuilder() .build();
User user = new UserBuilder()
.withName(“Alan”)
.withPassword(“secret”).build();
Build method
Safe Defaults
Chainable
Imperative Example
Given a User "dave" exists with password "secret"
And I am not logged in
When I navigate to the home page
Then I am redirected to the login form
....
Refactored to be Declarative
Given I am an unauthenticated User
When I attempt to view some restricted content
Then I am shown a login form
When I authenticate with valid credentials
….
private UserDescription user;
@Given("^I am an … $")
public void unauthenticated_user() {
user = new UserBuilder().build();
…
}
Declarative Example
private UserDescription user;
@Given("^ a User … $")
public void a_user(String name, password) {
user = new UserBuilder()
.withName(name)
.withPassword(password).build();
}
private UserDescription user;
private UserBuilder userBuilder = new UserBuilder();
@Given("^I am an … $")
public void unauthenticated_user() {
user = userBuilder.build();
}
@Given("^an email address $")
public void user_email(String emailAddress) {
userBuilder.withEmail(emailAddress);
user = userBuilder.build();
}
public class IssueBuilder {
String summary = “Default Summary”;
Project project = new ProjectBuilder().build();
String reporter = new UserBuilder().build();
…
public IssueBuilder withProject(Project project) {
this.project = project;
return this;
}
public IssueDescription build() {…}
}
Issue issue = new IssueBuilder()
.withSummary(“Icon hover bug”).build();
.withReporter(
new UserBuilder().withName(“Alan”)
.build())
.build();
public class IssueBuilder {
…
Project project = null;
…
public IssueDescription build() {
if (project == null) {
project = new ProjectBuilder().build();
}
…
}
}
Unique
Factories
Create test data with the most
appropriate tools and
using a sensible DSL
Questions
Alan Parkinson
CEO, Hindsight Software Ltd
alan.parkinson@hindsightsoftware.co.uk
@alan_parkinson
Links
Test Data Builders: an alternate to the Object
Mother pattern - http://ow.ly/jEYkf
NatPryce.com

More Related Content

PPTX
Test Data Builder Pattern
PPTX
Entity framework 6
PDF
Кирилл Латыш "ERP on Websockets"
PDF
Euruko 2009 - DataObjects
PDF
Client Server Communication on iOS
PPTX
Testing database content with DBUnit. My experience.
PDF
New Features of JSR 317 (JPA 2.0)
PPTX
Entity Framework Database and Code First
Test Data Builder Pattern
Entity framework 6
Кирилл Латыш "ERP on Websockets"
Euruko 2009 - DataObjects
Client Server Communication on iOS
Testing database content with DBUnit. My experience.
New Features of JSR 317 (JPA 2.0)
Entity Framework Database and Code First

What's hot (20)

PDF
Advanced Core Data
PDF
Building a Backend with Flask
PPTX
Entity Framework: Code First and Magic Unicorns
KEY
Core Data
PPTX
01 session tracking
PPTX
Agile methodologies based on BDD and CI by Nikolai Shevchenko
PDF
Distributing information on iOS
PDF
How to connect database file to a 3-Tier Architecture Application and obtain ...
PPTX
Getting started with entity framework
ODP
An Introduction to Quill
PPT
Backbone.js
DOCX
Labs And Walkthroughs
PPTX
Microsoft Entity Framework
PDF
Mvc acchitecture
PPTX
Presentation
PDF
Rabin Shrestha: Data Validation and Sanitization in WordPress
PPTX
Android Database
PPTX
Simple blog wall creation on Java
PPTX
Design pattern proxy介紹 20130805
PDF
Persistence on iOS
Advanced Core Data
Building a Backend with Flask
Entity Framework: Code First and Magic Unicorns
Core Data
01 session tracking
Agile methodologies based on BDD and CI by Nikolai Shevchenko
Distributing information on iOS
How to connect database file to a 3-Tier Architecture Application and obtain ...
Getting started with entity framework
An Introduction to Quill
Backbone.js
Labs And Walkthroughs
Microsoft Entity Framework
Mvc acchitecture
Presentation
Rabin Shrestha: Data Validation and Sanitization in WordPress
Android Database
Simple blog wall creation on Java
Design pattern proxy介紹 20130805
Persistence on iOS
Ad

Similar to Creating data with the test data builder pattern (17)

PDF
Transformando os pepinos do cliente no código de testes da sua aplicação
DOC
Tutorial asp.net
PPTX
Android and firebase database
PDF
第一次用Parse就深入淺出
DOC
Creating a Simple PHP and MySQL-Based Login System
PPTX
Security in laravel
PDF
Continuous integration using thucydides(bdd) with selenium
PPTX
Spring Security 3
PDF
Symfony Guard Authentication: Fun with API Token, Social Login, JWT and more
ODP
My app is secure... I think
PDF
JavaScript & Cloud: the AWS JS SDK and how to work with cloud resources
PDF
From 0 to Spring Security 4.0
PDF
6 Things You Didn't Know About Firebase Auth
PPT
Form demoinplaywithmysql
PDF
InheritedWidget is your friend - GDG London (2018-08-08)
PDF
Lesson_07_Spring_Security_Register_NEW.pdf
PDF
Webauthn Tutorial
Transformando os pepinos do cliente no código de testes da sua aplicação
Tutorial asp.net
Android and firebase database
第一次用Parse就深入淺出
Creating a Simple PHP and MySQL-Based Login System
Security in laravel
Continuous integration using thucydides(bdd) with selenium
Spring Security 3
Symfony Guard Authentication: Fun with API Token, Social Login, JWT and more
My app is secure... I think
JavaScript & Cloud: the AWS JS SDK and how to work with cloud resources
From 0 to Spring Security 4.0
6 Things You Didn't Know About Firebase Auth
Form demoinplaywithmysql
InheritedWidget is your friend - GDG London (2018-08-08)
Lesson_07_Spring_Security_Register_NEW.pdf
Webauthn Tutorial
Ad

More from Alan Parkinson (13)

PPTX
Testing requirements with BDD
PPTX
Baking in the cloud with packer and puppet
PPTX
Decapitating Selenium with JavaScript
PPTX
Pull requests and testers can be friends
PPTX
What is Continuous Delivery?
PPTX
Cross browser Testing JavaScript
PPTX
Why we used Feature Branching
PPTX
Test automation with Cucumber-JVM
PPTX
A Quick overview of Behaviour Driven Development (BDD)
PPTX
Cross-browser unit testing JavaScript
PPTX
Acceptance test styles - Imperative vs Declarative
PPTX
Continuous Deployment Pipeline with maven
PPTX
Feature branching a release day painkiller
Testing requirements with BDD
Baking in the cloud with packer and puppet
Decapitating Selenium with JavaScript
Pull requests and testers can be friends
What is Continuous Delivery?
Cross browser Testing JavaScript
Why we used Feature Branching
Test automation with Cucumber-JVM
A Quick overview of Behaviour Driven Development (BDD)
Cross-browser unit testing JavaScript
Acceptance test styles - Imperative vs Declarative
Continuous Deployment Pipeline with maven
Feature branching a release day painkiller

Recently uploaded (20)

PPT
Teaching material agriculture food technology
PDF
Empathic Computing: Creating Shared Understanding
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPTX
MYSQL Presentation for SQL database connectivity
PDF
cuic standard and advanced reporting.pdf
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Electronic commerce courselecture one. Pdf
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
KodekX | Application Modernization Development
PDF
Machine learning based COVID-19 study performance prediction
Teaching material agriculture food technology
Empathic Computing: Creating Shared Understanding
Diabetes mellitus diagnosis method based random forest with bat algorithm
The Rise and Fall of 3GPP – Time for a Sabbatical?
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
MYSQL Presentation for SQL database connectivity
cuic standard and advanced reporting.pdf
Mobile App Security Testing_ A Comprehensive Guide.pdf
Spectral efficient network and resource selection model in 5G networks
Building Integrated photovoltaic BIPV_UPV.pdf
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
20250228 LYD VKU AI Blended-Learning.pptx
“AI and Expert System Decision Support & Business Intelligence Systems”
Review of recent advances in non-invasive hemoglobin estimation
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Electronic commerce courselecture one. Pdf
MIND Revenue Release Quarter 2 2025 Press Release
KodekX | Application Modernization Development
Machine learning based COVID-19 study performance prediction

Creating data with the test data builder pattern

Editor's Notes

  • #3: HowWhenWhy
  • #4: To isolate data between tests, script cleans and populates the databaseRequires direct access to the database
  • #5: SQL Scripts are brittle to changePortability issues between database vendorsHigh maintenance costDifficult to create dataHard write by handSmall sets of data created – often reused across many tests.Run Application, add data and create Script from Database DumpLots of small variationsFor large sets of tests data schema changes are expensiveCan’t be used with Concurrent / Parallel Test ExecutionIgnores business rules on data – Script my load data that does not follow the correct business rules, cause test to fail. Hard to debugLimits reuse of Test artifactsCan’t access databases on production systems - NO smoke testing deployments –
  • #6: Our Applications expose API’s all the timeREST, SOAP and RMI to name a fewUse them to create our test dataOn Demand – Given StepDevelopers maintain the public API – receives free maintenanceCode reuse – Code can be reused for Testing the REST services.Tests can be reused for Smoke testing deploymentsAs it doesn't clean the database. Requires generated data to be uniqueIgnores system state - the same tests can be repeatedly executed with the same result
  • #7: Public API code - Large messy code for creating test data on demandNice abstraction is requiredReadable test setup codeCode reuseEasy and low maintenanceNat PryceCreate a builder for each class or resourceHas an instance variable for each constructor parameterInitialises its instance variables to commonly used or safe valuesHas a `build` method that creates a new object using the values in its instance variablesHas "chainable" public methods for overriding the values in its instance variables.
  • #8: Simplest example of a builder used in Unit testsAll builders feature a build method - No parametersReturns value objectInstead we would make REST/API calls to our
  • #9: Sensible defaults Click - Can be overriddenWritten a fluent styleEasy to read
  • #10: Returns object describing the remotely created datae.g. unique IDIssueBuilder would return the Key of the created Issue.Even if the Any other useful information that is required by the test
  • #11: The imperative style uses highly reusable granular steps which outlines much of the user interface. This binds the scenario to that UI and requires more design decisions made up front.Makes the Scenario brittle to minor changes in UI when no Behaviour or functionality has changed.
  • #12: Each step states an idea.Sometimes it’s not really clear precisely what is being doneThe username and password detail has been pushed inside the test implementationWe don’t care about these details in this example – It doesn’t add anythingUse sensible defaults for these values – Data Builder also uses sensible defaults.
  • #16: RelationshipsRefactor build method to lazily initialize
  • #17: Sensible defaults Can be overriddenWritten a fluent styleEasy to readEmbedding builders
  • #18: As we are creating remote objects, defaults should lazily initialized to avoid performance penalty
  • #19: ID’s are best generated - previously run the same test suite and have not cleared the database, manually created unique ID’s could already be in use.Randomness - Repeating the test should not generate the same IDWe have found Hashes work quite well for Alphanumeric generationIssue – generates unique ID in the dataProject – requires us to generate a unique IDProject ID is up to 10 characters long and Alpha onlyGenerated IDs avoid clashes with stale dataHashes – MD5Seeding data generation ImportantTest method name useful componentRandom numberBusiness rules – Data length and typeAlpha only string generator
  • #20: Different product versions/configurationsDifferent data formatsDifferent devicesCan be supported by the Abstract Factory patternCreate families of builders to support them
  • #21: Avoid SQLUse exposed API’sGenerate Unique dataData Builder PatternFactories for your Data Builders
  • #24: Test Data Builders: an alternate to the Object Mother patternCreate objects with complex constructors in Unit TestsHas an instance variable for each constructor parameterInitialises its instance variables to commonly used or safe valuesHas a `build` method that creates a new object using the values in its instance variablesHas "chainable" public methods for overriding the values in its instance variables.