SlideShare a Scribd company logo
1 of 45
Download to read offline
grails
                         build-test-data
                             plugin




                         created by Ted Naleid and Joe Hoover


Tuesday, July 14, 2009
creating test data with
                            groovy is easy!


Tuesday, July 14, 2009
iterators
                                     ["Alice", "Bob", "Carol", "Dave"].each {
                         closures    }
                                        new Author(name: it).save()




       syntactic sugar


Tuesday, July 14, 2009
modeling your domain in
                   grails is easy!


Tuesday, July 14, 2009
a book belongs        class Book {
                             String title
                             static belongsTo = [author: Author]
     to an author        }




       an author has     class Author {
                             String name
        many books       }
                             static hasMany = [books: Book]




Tuesday, July 14, 2009
class User {
                                   String login
                                    String password
                                   String email
                                   Date birthDate

                                    static constraints = {
                                       login(size: 5..15,
                 constraints                  blank: false,
                                              unique: true)
                                        password(size: 5..15,
                                                 blank: false)
                                        email(email: true,
                                              blank: false)
                                        birthDate(max: new Date())
                                   }
                               }




Tuesday, July 14, 2009
test data must pass constraints



 def user = new User(
   login: “tnaleid”,
   password: “sekrit1”,
   birthDate: new Date() - (365 * 36)
 ).save()




Tuesday, July 14, 2009
whoops! missed an attribute!



 def user = new User(
   login: “tnaleid”,
   password: “sekrit1”,
   email: “contact@naleid.com”,
   age: new Date() - (365 * 36)
 ).save()




Tuesday, July 14, 2009
constrained attributes are required
   even if your test doesn’t care about
                   them

 def user = new User(
   login: “tnaleid”,
   password: “sekrit”,
   email: “contact@naleid.com”,
   birthDate: new Date() - (365 * 36)
 ).save()

 // service looks up user in DB by username and deletes it
 assertTrue userService.deleteByUsername(“tnaleid”)


Tuesday, July 14, 2009
problem multiplied by
              complex domain models




Tuesday, July 14, 2009
agile + code coverage =
                       lots of tests


Tuesday, July 14, 2009
you need to add a new
                         constraint...
                    what happens to all the
                            tests?

Tuesday, July 14, 2009
Tuesday, July 14, 2009
creating maintainable test
                        data is hard!



Tuesday, July 14, 2009
existing test data
                         creation strategies


Tuesday, July 14, 2009
void testTenDollarPurchase() {
                             def author = new Author(
                                 name: “David Foster Wallace”
                             ).save()
                              Book book = new Book(
                                 author: author,
                                   title: "The Pale King",
                                   published: new Date(),
                                   price: 10.00 as BigDecimal
                             ).save()
                          
     copy/paste/         }
                             def ord = service.orderBook(book.id) 
                            //... test assertions

    modify for every     void testTwentyDollarPurchase() {

     test method             def author = new Author(
                                 name: “David Foster Wallace”
                             ).save()
                              Book book = new Book(
                                 author: author,
                                   title: "Infinite Jest",
                                   published: new Date(),
                                   price: 20.00 as BigDecimal
                             ).save()
                          
                             def ord = service.orderBook(book.id) 
                            //... test assertions
                         }


Tuesday, July 14, 2009
def author

                         void setUp() {
                             author = new Author(
                                 name: “David Foster Wallace”
                             ).save()
                         }

                         void testTenDollarPurchase() {
                             Book book = new Book(
                                 author: author,
                                 title: "The Pale King",
use setUp method                 published: new Date(),
                                 price: 10.00 as BigDecimal
                             ).save()
 to share objects         
                            def order = service.orderBook(book.id) 

   across tests          }
                            //... test assertions


                         void testTwentyDollarPurchase() {
                             Book book = new Book(
                                 author: author,
                                 title: "Infinite Jest",
                                 published: new Date(),
                                 price: 20.00 as BigDecimal
                             ).save()
                          
                            def result = service.orderBook(book.id) 
                            //... test assertions
                         }
Tuesday, July 14, 2009
class AuthorObjectMother {
                             static dfw() {
                                 return new Author(
                                     name: “David Foster Wallace”
                                 ).save()
                             }
                         }

                         class BookObjectMother {
                             static thePaleKing() {
                                 return new Book(
                                     author: AuthorObjectMother.dfw(),
                                     title: “The Pale King”,
                                     published: new Date(),
                                     price: 10.00 as BigDecimal
                                 ).save()

         object mother       }
                             static infiniteJest() {
                                 return new Book(
                                     author: AuthorObjectMother.dfw(),

            pattern                  title: “Infinite Jest”,
                                     published: new Date(),
                                     price: 20.00 as BigDecimal
                                 ).save()
                             }
                         }

                         testTenDollarPurchase() { 
                             Book book = BookObjectMother.thePaleKing()
                             def result = service.orderBook(book.id) 
                             //... test assertions
                         }

                         void testTwentyDollarPurchase() {
                             Book book = BookObjectMother.infiniteJest() 
                             def result = service.orderBook(book.id) 
                             //... test assertions
                         }
Tuesday, July 14, 2009
// fixtures/dfwBooks.groovy:
                         fixture {
                             davidFosterWallace(Author) {
                                 name = “David Foster Wallace”
                             }
                             thePaleKing(Book) {
                                    author = davidFosterWallace
                                    title = "The Pale King"
                                    published = new Date()
                                    price = 10.00 as BigDecimal
                             }
                             infiniteJest(Book) {
                                   author = davidFosterWallace
                                   title = "Infinite Jest"
                                   published = new Date()

  builder DSL / test     }
                             }
                                   price = 20.00 as BigDecimal



       fixtures          // test class ...
                         def fixtureLoader
                         void testTenDollarPurchase() {
                              fixtureLoader.load("dfwBooks")
                              Book book = Book.findByTitle(“The Pale King”)

                             def result = service.orderBook(book.id) 
                             //... test assertions
                         }

                         void testTenDollarPurchase() {
                              fixtureLoader.load("dfwBooks")
                              Book book = Book.findByTitle(“Infinite Jest”)
                              def result = service.orderBook(book.id) 
                            //... test assertions
                         }
Tuesday, July 14, 2009
all of these strategies strive
                      to DRY up your test data
                                creation




Tuesday, July 14, 2009
but all of them repeat the same
            rules specified in the constraints

Tuesday, July 14, 2009
void testTenDollarPurchase() {
                             Book book = new Book(
                                 price: 10.00 as BigDecimal
                             )
                             mockDomain(Book, [book])

grails does have             def order = service.orderBook(book.id)
                             //...test assertions
mocks ... but what       }


 are they really         void testTwentyDollarPurchase() {
                            Book book = new Book(
     testing?                )
                                 price: 20.00 as BigDecimal

                             mockDomain(Book, [book])
                          
                            def result = service.orderBook(book) 
                            //... test assertions
                         }




Tuesday, July 14, 2009
void testPurchaseBookService() {
                                        def author = new Author(
                                           name: "First Last",
                                        ).save()
                                        Book book = new Book(
   what if we could                        author: author,
                                           title: "title",
                                           published: new Date(),
      turn this                            price: 10.00 as BigDecimal
                                        ).save()
                                      
                                        def order = service.orderBook(book.id)
                                        //... test assertions
                                     }




                                     void testPurchaseBookService() {
                                       Book book = Book.build(
                                           price: 10.00 as BigDecimal
                         into this     )

                                         def result = service.orderBook(book)
                                         //... test assertions
                                     }
Tuesday, July 14, 2009
you can with the
                         build-test-data plugin


Tuesday, July 14, 2009
build-test-data
                          advantages


Tuesday, July 14, 2009
testing data documents
                      what’s being tested


Tuesday, July 14, 2009
only specify values the
                                test uses


Tuesday, July 14, 2009
test coupling is
                           eliminated


Tuesday, July 14, 2009
you’re executing real
                          GORM code paths


Tuesday, July 14, 2009
unrelated domain
                         changes won’t break
                              your tests


Tuesday, July 14, 2009
build-test-data usage



Tuesday, July 14, 2009
class Author {
                                String name
                                static hasMany = [books: Book]
                            }
               our domain   class Book {
                                String title
                                static belongsTo = [author: Author]
                            }




Tuesday, July 14, 2009
just give me a   def book = Book.build()

                           assertNotNull book.author
               book        assertNotNull book.title




Tuesday, July 14, 2009
give me a book,
  but let me set the     def book = Book.build(title:“Infinite Jest”)


          title



Tuesday, July 14, 2009
let me tweak the      def book = Book.build(author:

                         )
                             Author.build(name: “Charlie Stross”)

     book’s author



Tuesday, July 14, 2009
build-test-data features



Tuesday, July 14, 2009
‣   Domain objects (1..1, 1..N, N..N)
                         ‣   Embedded domain objects

     build-test-data     ‣
                         ‣
                             String
                             Boolean
       supports all      ‣
                         ‣
                             Number (Integer, Long, Float, etc)
                             Byte
     known attribute     ‣   Date

          types          ‣
                         ‣
                             Enum
                             JodaTime
                         ‣   Any other hibernate persistable class
                             with a zero-argument constructor




Tuesday, July 14, 2009
‣   nullable
                         ‣   blank
                         ‣   inList
                         ‣   max
                         ‣   maxSize

   automatic             ‣
                         ‣
                             min
                             minSize
constraint support       ‣
                         ‣
                             range
                             scale
                         ‣   size
                         ‣   url
                         ‣   creditCard
                         ‣   email




Tuesday, July 14, 2009
manual constraint        ‣
                         ‣
                             matches (regular expressions)
                             validator (user-defined constraint)
    support              ‣   unique




Tuesday, July 14, 2009
configuration file lets you customize
         static attribute values


 // grails-app/conf/TestDataConfig.groovy

 testDataConfig {
     sampleData = {
         Publisher {
             name = “Pragmatic Bookshelf” // default unless overridden
         }
     }
 }



Tuesday, July 14, 2009
configuration file lets you customize
       dynamic attribute values


 // grails-app/conf/TestDataConfig.groovy

 testDataConfig {
     sampleData = {
         ‘com.example.Hotel’ {
             def i = 1
             name = {-> “name${i++}” } // “name1”, “name2”, ... “nameN”
         }
     }
 }


Tuesday, July 14, 2009
build-test-data installation




                              grails install-plugin build-test-data




Tuesday, July 14, 2009
live coding demo



Tuesday, July 14, 2009
links
                                         build-test-data home
                         http://bitbucket.org/tednaleid/grails-test-data/wiki/Home

                                            intro blog post
        http://naleid.com/blog/2009/04/14/grails-build-test-data-01-plugin-released/




                                   photo credits
                http://www.flickr.com/photos/kaptainkobold/3406169798/in/set-1058884

                          http://commons.wikimedia.org/wiki/File:Domain_model.png

                http://www.flickr.com/photos/nickwheeleroz/2474196275/in/photostream




Tuesday, July 14, 2009
Questions?



Tuesday, July 14, 2009

More Related Content

Recently uploaded

New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Neo4j
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfjimielynbastida
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 

Recently uploaded (20)

New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdf
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 

Featured

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by HubspotMarius Sescu
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTExpeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 

Featured (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

Grails build-test-data Plugin

  • 1. grails build-test-data plugin created by Ted Naleid and Joe Hoover Tuesday, July 14, 2009
  • 2. creating test data with groovy is easy! Tuesday, July 14, 2009
  • 3. iterators ["Alice", "Bob", "Carol", "Dave"].each { closures } new Author(name: it).save() syntactic sugar Tuesday, July 14, 2009
  • 4. modeling your domain in grails is easy! Tuesday, July 14, 2009
  • 5. a book belongs class Book { String title static belongsTo = [author: Author] to an author } an author has class Author { String name many books } static hasMany = [books: Book] Tuesday, July 14, 2009
  • 6. class User { String login String password String email Date birthDate static constraints = { login(size: 5..15, constraints blank: false, unique: true) password(size: 5..15, blank: false) email(email: true, blank: false) birthDate(max: new Date()) } } Tuesday, July 14, 2009
  • 7. test data must pass constraints def user = new User( login: “tnaleid”, password: “sekrit1”, birthDate: new Date() - (365 * 36) ).save() Tuesday, July 14, 2009
  • 8. whoops! missed an attribute! def user = new User( login: “tnaleid”, password: “sekrit1”, email: “contact@naleid.com”, age: new Date() - (365 * 36) ).save() Tuesday, July 14, 2009
  • 9. constrained attributes are required even if your test doesn’t care about them def user = new User( login: “tnaleid”, password: “sekrit”, email: “contact@naleid.com”, birthDate: new Date() - (365 * 36) ).save() // service looks up user in DB by username and deletes it assertTrue userService.deleteByUsername(“tnaleid”) Tuesday, July 14, 2009
  • 10. problem multiplied by complex domain models Tuesday, July 14, 2009
  • 11. agile + code coverage = lots of tests Tuesday, July 14, 2009
  • 12. you need to add a new constraint... what happens to all the tests? Tuesday, July 14, 2009
  • 14. creating maintainable test data is hard! Tuesday, July 14, 2009
  • 15. existing test data creation strategies Tuesday, July 14, 2009
  • 16. void testTenDollarPurchase() { def author = new Author( name: “David Foster Wallace” ).save() Book book = new Book( author: author, title: "The Pale King", published: new Date(), price: 10.00 as BigDecimal ).save()   copy/paste/ } def ord = service.orderBook(book.id)  //... test assertions modify for every void testTwentyDollarPurchase() { test method def author = new Author( name: “David Foster Wallace” ).save() Book book = new Book( author: author, title: "Infinite Jest", published: new Date(), price: 20.00 as BigDecimal ).save()   def ord = service.orderBook(book.id)  //... test assertions } Tuesday, July 14, 2009
  • 17. def author void setUp() { author = new Author( name: “David Foster Wallace” ).save() } void testTenDollarPurchase() { Book book = new Book( author: author, title: "The Pale King", use setUp method published: new Date(), price: 10.00 as BigDecimal ).save() to share objects   def order = service.orderBook(book.id)  across tests } //... test assertions void testTwentyDollarPurchase() { Book book = new Book( author: author, title: "Infinite Jest", published: new Date(), price: 20.00 as BigDecimal ).save()   def result = service.orderBook(book.id)  //... test assertions } Tuesday, July 14, 2009
  • 18. class AuthorObjectMother { static dfw() { return new Author( name: “David Foster Wallace” ).save() } } class BookObjectMother { static thePaleKing() { return new Book( author: AuthorObjectMother.dfw(), title: “The Pale King”, published: new Date(), price: 10.00 as BigDecimal ).save() object mother } static infiniteJest() { return new Book( author: AuthorObjectMother.dfw(), pattern title: “Infinite Jest”, published: new Date(), price: 20.00 as BigDecimal ).save() } } testTenDollarPurchase() {  Book book = BookObjectMother.thePaleKing() def result = service.orderBook(book.id)  //... test assertions } void testTwentyDollarPurchase() { Book book = BookObjectMother.infiniteJest()  def result = service.orderBook(book.id)  //... test assertions } Tuesday, July 14, 2009
  • 19. // fixtures/dfwBooks.groovy: fixture { davidFosterWallace(Author) { name = “David Foster Wallace” } thePaleKing(Book) { author = davidFosterWallace title = "The Pale King" published = new Date() price = 10.00 as BigDecimal } infiniteJest(Book) { author = davidFosterWallace title = "Infinite Jest" published = new Date() builder DSL / test } } price = 20.00 as BigDecimal fixtures // test class ... def fixtureLoader void testTenDollarPurchase() { fixtureLoader.load("dfwBooks") Book book = Book.findByTitle(“The Pale King”) def result = service.orderBook(book.id)  //... test assertions } void testTenDollarPurchase() { fixtureLoader.load("dfwBooks") Book book = Book.findByTitle(“Infinite Jest”) def result = service.orderBook(book.id)  //... test assertions } Tuesday, July 14, 2009
  • 20. all of these strategies strive to DRY up your test data creation Tuesday, July 14, 2009
  • 21. but all of them repeat the same rules specified in the constraints Tuesday, July 14, 2009
  • 22. void testTenDollarPurchase() { Book book = new Book( price: 10.00 as BigDecimal ) mockDomain(Book, [book]) grails does have def order = service.orderBook(book.id) //...test assertions mocks ... but what } are they really void testTwentyDollarPurchase() { Book book = new Book( testing? ) price: 20.00 as BigDecimal mockDomain(Book, [book])   def result = service.orderBook(book)  //... test assertions } Tuesday, July 14, 2009
  • 23. void testPurchaseBookService() { def author = new Author( name: "First Last", ).save() Book book = new Book( what if we could author: author, title: "title", published: new Date(), turn this price: 10.00 as BigDecimal ).save()   def order = service.orderBook(book.id) //... test assertions } void testPurchaseBookService() { Book book = Book.build( price: 10.00 as BigDecimal into this ) def result = service.orderBook(book) //... test assertions } Tuesday, July 14, 2009
  • 24. you can with the build-test-data plugin Tuesday, July 14, 2009
  • 25. build-test-data advantages Tuesday, July 14, 2009
  • 26. testing data documents what’s being tested Tuesday, July 14, 2009
  • 27. only specify values the test uses Tuesday, July 14, 2009
  • 28. test coupling is eliminated Tuesday, July 14, 2009
  • 29. you’re executing real GORM code paths Tuesday, July 14, 2009
  • 30. unrelated domain changes won’t break your tests Tuesday, July 14, 2009
  • 32. class Author { String name static hasMany = [books: Book] } our domain class Book { String title static belongsTo = [author: Author] } Tuesday, July 14, 2009
  • 33. just give me a def book = Book.build() assertNotNull book.author book assertNotNull book.title Tuesday, July 14, 2009
  • 34. give me a book, but let me set the def book = Book.build(title:“Infinite Jest”) title Tuesday, July 14, 2009
  • 35. let me tweak the def book = Book.build(author: ) Author.build(name: “Charlie Stross”) book’s author Tuesday, July 14, 2009
  • 37. Domain objects (1..1, 1..N, N..N) ‣ Embedded domain objects build-test-data ‣ ‣ String Boolean supports all ‣ ‣ Number (Integer, Long, Float, etc) Byte known attribute ‣ Date types ‣ ‣ Enum JodaTime ‣ Any other hibernate persistable class with a zero-argument constructor Tuesday, July 14, 2009
  • 38. nullable ‣ blank ‣ inList ‣ max ‣ maxSize automatic ‣ ‣ min minSize constraint support ‣ ‣ range scale ‣ size ‣ url ‣ creditCard ‣ email Tuesday, July 14, 2009
  • 39. manual constraint ‣ ‣ matches (regular expressions) validator (user-defined constraint) support ‣ unique Tuesday, July 14, 2009
  • 40. configuration file lets you customize static attribute values // grails-app/conf/TestDataConfig.groovy testDataConfig { sampleData = { Publisher { name = “Pragmatic Bookshelf” // default unless overridden } } } Tuesday, July 14, 2009
  • 41. configuration file lets you customize dynamic attribute values // grails-app/conf/TestDataConfig.groovy testDataConfig { sampleData = { ‘com.example.Hotel’ { def i = 1 name = {-> “name${i++}” } // “name1”, “name2”, ... “nameN” } } } Tuesday, July 14, 2009
  • 42. build-test-data installation grails install-plugin build-test-data Tuesday, July 14, 2009
  • 43. live coding demo Tuesday, July 14, 2009
  • 44. links build-test-data home http://bitbucket.org/tednaleid/grails-test-data/wiki/Home intro blog post http://naleid.com/blog/2009/04/14/grails-build-test-data-01-plugin-released/ photo credits http://www.flickr.com/photos/kaptainkobold/3406169798/in/set-1058884 http://commons.wikimedia.org/wiki/File:Domain_model.png http://www.flickr.com/photos/nickwheeleroz/2474196275/in/photostream Tuesday, July 14, 2009