SlideShare a Scribd company logo
1 of 44
GRAILS SPOCK
TESTING
Agenda
1. Testingoverview
2. Understanding UnitTesting
3. Spock UnitTesting
4. Writing Unit test cases
5. Demo
6. Exercise
What do we test ?
What a program issupposed to do
==
What the program actuallydoes
Motivation
Peopleare not perfect
We make errorsin design and code
Testing is an Investment
Over the time the tests build, the
early investment in writingtest
cases pays dividends later as the
sizeof the application grows
A way Of Thinking
• Design and Coding are creative while Testing isDestructive
• Primarygoal isto break the software
• Very often the same person does coding and testing. He needs a
splitpersonality
• One needs to be paranoid and malicious
• Surprisinglyhard to do as people don't like finding themselves making
mistakes
MailService.groovy
• Testing isa process of executing software with the intention of finding
errors
• Good testing has high probability of finding yet undiscovered errors
• Successful testing discoverserrors
• Ifit did not, need to ask whether our testing approach isgood or not
Integral Part of Development
• Testingneedstobe integralpartateach levelof development
• Types:
• Unit testing (whitebox)
• Integration testing (whitebox)
• Functional testing (blackbox)
• Acceptance testing
Understanding Unit testing
• Individual units of source code are tested
• A unit isthe smallest testable part of the application
• Each test case isindependent of the others
• Substituteslike mock, stubs areused
• Testsindividual methods or blocks without considering the
surrounding infrastructure
• A unit test provides a strict contract that a piece of code MUSTsatisfy
Disadvantages of Unit testing
• Test cases ‐written to suit programmer’simplementation(not
necessarily specification)
• The actual database or external file isnever tested directly
• Highly reliant on Refactoring and Programming skils
Advantages of Unit testing
• Facilitates change
• Allows refactoring at a later date and makes sure the
module stil workscorrectly
• SimplifiesIntegration
• Byremoving uncertainty among units themselves
• Acts asDocumentation
• Acts as a living documentation of a system
Advantages of Unit testing
• Evolvesdesign
• In“Test Driven Approach”, the unit test may take the
place of formal design. Each unit test case acts as a
design element for classes, methods and behaviour
• Improves the Quality Of the Software
Spock
• A developer testing framework for Java and Groovy application
• Based onGroovy
• What makes it stand out from the crowd isitsbeautiful and highly
expressive specification language
Basics
Spockletsyouwritespecificationsthatdescribeexpected features
(properties,aspects)exhibitedby a systemof interest
import spock.lang.*
Package spock.lang contains themostimportanttypesfor writing
specifications
Specification
• A specification isrepresented as a Groovy class that extends from
spock.lang.Specification, e.g.,
• class MyFirstSpecification extends Specification{
• }
• Class names of Spock tests must end in either “Spec” or
“Specification”. Otherwise the Grails test runner won't find them.
… contd
• Specification contains a number of useful methods for writing
specifications
• Instructs JUnit to run specification withSputnik, Spock's JUnitrunner
Fields
• Declarations:
• def obj =newClass()
• @Shared res =new VeryExpensiveResource()
Fixture Methods
• Fixture methods are responsible for setting up and cleaning up the
environment in which feature methods are run.
• def setup(){}
• def cleanup(){}
• def setupSpec(){}
• def cleanupSpec() {}
Blocks
• A test case can have following blocks:
• setup
• when //forstimulus
• then //output comparison
• expect
• where
Example
Expect Block
• Itisuseful in situations where itis
more natural to describestimulus
and expected response in a
singleexpression
Where block
• Itisused to write data-driven featuremethods
Data Driven Testing
• Itisuseful to exercise the same test code multiple times, with varying
inputs and expected results.
• Itisa firstclass feature in Spock
Data Tables
• A convenient way to exercise a
feature method with a fixed set
of data
Data Pipes
• A data pipe, indicated by the
left-shift (<<)operator, connects a
data variable to a data provider.
@Unroll
• A method annotated with @Unrol will have itsiterations reported
independently
Exception Conditions
• They are used to describe that a when block should throw an
exception
Mocking
• Mock objects literally implement (or extend) the type they stand in
for
• Initiallymock objects have no behavior
• Calling methods on them is allowed but has no effect otherthan
returning the default value for the method’s return type, except for
equals and toString
• A mock object isonly equal to itself, has a unique hash code, and a
string representation that includes the name of the type it represents
..contd.
• Thisdefault behavior isoverrideable by stubbing the methods
• Mock objects are created with the MockingApi.Mock()
• def subscriber =Mock(Subscriber)
• Subscriber subsriber =Mock()
mockDomain()
• Takesa class and mock implementations of all the domain class
methods accessible onit
• mockDomain() provides a versionof domain classes in which the
database issimply listof domain instances in memory.
• mockDomain(Person, [persons])
• All mocked methods like save(),get() etc work against thislist.
mockForConstraintsTest()
• Highly specialized mocking for domain classes and command
objects that allows you to check whether the constraints are
behaving as expectedor not
• Itsimply adds a validate() method to a given domain class.
• mockForConstraintsTests(Person, [persons])
Test Mixins
• Since Grails 2.0,a collection of unit testing mixinsisprovided by Grails,
that enhances the behavior of a typical Junit or Spock test
• Common examplesare:
• @TestFor(BookController)
• @Mock([Book,Author])
TestFor Annotation
• The TestFor annotation defines a class under test and will
automatically create a field for the type of class under test
• For example, @TestFor(BookController) this will automaticallycreate
“controller” field
• IfTestForwas defined for a service then a “service” field would be
created
Mock Annotation
• The Mock annotation creates a mock version of any collaborators
• There isan in-memory implementation of GORM that will simulate
most interactions with GORM API
• For those interactions that are not automatically mocked, you need
to define mocksprogrammatically
Cardinality
• The cardinality of an interaction describes how often a method call is
expected. Itcan either be a fixed number or a range
• 1 *subscriber.receive(“hello”)
• 0..1)*subscriber.receive(“hello”)
• 0.._)*subscriber.receive(“hello”)
• 1 *subscriber._(“hello”)
Verification Of Interactions
Stubbing
• Stubbing isthe act of making collaborators respond to method calls
in acertain way
• Inother words stubbing isjustproviding dummy implementation of a
method
Stubbing Examples
• Returning FixedValues:
• subscriber.receive(_)>>”Ok”
• Toreturn different values on successive invocations, use the triple-
right-shift(>>>)operator
• subscriber.receive(_) >>>["ok","error","error", "ok"]
...contd.
• Accessing Method Arguments
• subscriber.receive(_) >>{String message ->message.size()
>3 ? "ok":"fail"}
• Throw anexception:
• subscriber.receive(_) >>{throw new InternalError("ouch")}
Test Code Coverage Plugin
• Creates test code coverage for your code
• Add dependency:
• test ":code-coverage:1.2.6"
• Torun:
• grails test-app -coverage
• The script will create HTLMreports and place them in the
tests/report/cobertura directory.
References
• https://code.google.com/p/spock/wiki/SpockBasics
• https://code.google.com/p/spock/wiki/GettingStarted
• http://docs.spockframework.org/en/latest/
• http://meetspock.appspot.com/
• http://naleid.com/blog/2012/05/01/upgrading-to-grails-2-unit-
testing/
Contact us
Our Office
Client
Location
Click Here To Know More!
Have more queries on Grails?
Talk to our GRAILS experts
Now!
Talk To Our Experts
Here's how the world's
biggest Grails team is
building enterprise
applications on Grails!

More Related Content

What's hot

Unit testing, UI testing and Test Driven Development in Visual Studio 2012
Unit testing, UI testing and Test Driven Development in Visual Studio 2012Unit testing, UI testing and Test Driven Development in Visual Studio 2012
Unit testing, UI testing and Test Driven Development in Visual Studio 2012
Jacinto Limjap
 

What's hot (20)

Embrace Unit Testing
Embrace Unit TestingEmbrace Unit Testing
Embrace Unit Testing
 
Junit and testNG
Junit and testNGJunit and testNG
Junit and testNG
 
How and what to unit test
How and what to unit testHow and what to unit test
How and what to unit test
 
Tdd & unit test
Tdd & unit testTdd & unit test
Tdd & unit test
 
Unit testing with java
Unit testing with javaUnit testing with java
Unit testing with java
 
.Net Unit Testing with Visual Studio 2010
.Net Unit Testing with Visual Studio 2010.Net Unit Testing with Visual Studio 2010
.Net Unit Testing with Visual Studio 2010
 
JUnit 5
JUnit 5JUnit 5
JUnit 5
 
Automated Unit Testing
Automated Unit TestingAutomated Unit Testing
Automated Unit Testing
 
Unit testing, UI testing and Test Driven Development in Visual Studio 2012
Unit testing, UI testing and Test Driven Development in Visual Studio 2012Unit testing, UI testing and Test Driven Development in Visual Studio 2012
Unit testing, UI testing and Test Driven Development in Visual Studio 2012
 
Simple Unit Testing With Netbeans 6.1
Simple Unit Testing With Netbeans 6.1Simple Unit Testing With Netbeans 6.1
Simple Unit Testing With Netbeans 6.1
 
Test driven development - JUnit basics and best practices
Test driven development - JUnit basics and best practicesTest driven development - JUnit basics and best practices
Test driven development - JUnit basics and best practices
 
All about unit testing using (power) mock
All about unit testing using (power) mockAll about unit testing using (power) mock
All about unit testing using (power) mock
 
TestNG vs. JUnit4
TestNG vs. JUnit4TestNG vs. JUnit4
TestNG vs. JUnit4
 
Unit testing with JUnit
Unit testing with JUnitUnit testing with JUnit
Unit testing with JUnit
 
JUnit & Mockito, first steps
JUnit & Mockito, first stepsJUnit & Mockito, first steps
JUnit & Mockito, first steps
 
testng
testngtestng
testng
 
Testing and Mocking Object - The Art of Mocking.
Testing and Mocking Object - The Art of Mocking.Testing and Mocking Object - The Art of Mocking.
Testing and Mocking Object - The Art of Mocking.
 
Testing In Java
Testing In JavaTesting In Java
Testing In Java
 
Java Testing With Spock - Ken Sipe (Trexin Consulting)
Java Testing With Spock - Ken Sipe (Trexin Consulting)Java Testing With Spock - Ken Sipe (Trexin Consulting)
Java Testing With Spock - Ken Sipe (Trexin Consulting)
 
Introduction to JUnit
Introduction to JUnitIntroduction to JUnit
Introduction to JUnit
 

Viewers also liked

Their most famous piece and why it was well know
Their most famous piece and why it was well knowTheir most famous piece and why it was well know
Their most famous piece and why it was well know
sathma
 
FUKUYAMA BASE WORKSHOP Vol14 Theme
FUKUYAMA BASE WORKSHOP Vol14 ThemeFUKUYAMA BASE WORKSHOP Vol14 Theme
FUKUYAMA BASE WORKSHOP Vol14 Theme
noteproject
 
Advertisement/ PowerPoint
Advertisement/ PowerPoint Advertisement/ PowerPoint
Advertisement/ PowerPoint
sathma
 
วัฏจักรของน้ำ
วัฏจักรของน้ำวัฏจักรของน้ำ
วัฏจักรของน้ำ
pongsakorn62
 
Roles for my group
Roles for my groupRoles for my group
Roles for my group
sathma
 
Integrate technology by expanding your toolkit pp
Integrate technology by expanding your toolkit ppIntegrate technology by expanding your toolkit pp
Integrate technology by expanding your toolkit pp
Ladue School District
 
Presentation of medivel
Presentation of medivelPresentation of medivel
Presentation of medivel
sathma
 
Medical terminology presentation 9
Medical terminology presentation 9Medical terminology presentation 9
Medical terminology presentation 9
arivera79
 
The reproductive system presentation
The reproductive system presentationThe reproductive system presentation
The reproductive system presentation
arivera79
 
Sanat
SanatSanat
Sanat
merve
 
MongoDB (Advanced)
MongoDB (Advanced)MongoDB (Advanced)
MongoDB (Advanced)
TO THE NEW | Technology
 
Advert on social media
Advert on social mediaAdvert on social media
Advert on social media
Aleksis
 

Viewers also liked (20)

Their most famous piece and why it was well know
Their most famous piece and why it was well knowTheir most famous piece and why it was well know
Their most famous piece and why it was well know
 
FUKUYAMA BASE WORKSHOP Vol14 Theme
FUKUYAMA BASE WORKSHOP Vol14 ThemeFUKUYAMA BASE WORKSHOP Vol14 Theme
FUKUYAMA BASE WORKSHOP Vol14 Theme
 
FUKUYAMA BASE WORKSHOP Vol17 Theme
FUKUYAMA BASE WORKSHOP Vol17 ThemeFUKUYAMA BASE WORKSHOP Vol17 Theme
FUKUYAMA BASE WORKSHOP Vol17 Theme
 
Advertisement/ PowerPoint
Advertisement/ PowerPoint Advertisement/ PowerPoint
Advertisement/ PowerPoint
 
วัฏจักรของน้ำ
วัฏจักรของน้ำวัฏจักรของน้ำ
วัฏจักรของน้ำ
 
Roles for my group
Roles for my groupRoles for my group
Roles for my group
 
Integrate technology by expanding your toolkit pp
Integrate technology by expanding your toolkit ppIntegrate technology by expanding your toolkit pp
Integrate technology by expanding your toolkit pp
 
Stores around cannon building
Stores around cannon buildingStores around cannon building
Stores around cannon building
 
Presentation of medivel
Presentation of medivelPresentation of medivel
Presentation of medivel
 
Mn powerpoint
Mn powerpointMn powerpoint
Mn powerpoint
 
Medical terminology presentation 9
Medical terminology presentation 9Medical terminology presentation 9
Medical terminology presentation 9
 
The reproductive system presentation
The reproductive system presentationThe reproductive system presentation
The reproductive system presentation
 
Sanat
SanatSanat
Sanat
 
MongoDB (Advanced)
MongoDB (Advanced)MongoDB (Advanced)
MongoDB (Advanced)
 
The Router Explained Rroosend
The Router Explained RroosendThe Router Explained Rroosend
The Router Explained Rroosend
 
4 planning section
4 planning section4 planning section
4 planning section
 
Grails and Ajax
Grails and AjaxGrails and Ajax
Grails and Ajax
 
Advert on social media
Advert on social mediaAdvert on social media
Advert on social media
 
Office 365 voor het onderwijs
Office 365 voor het onderwijsOffice 365 voor het onderwijs
Office 365 voor het onderwijs
 
American Revolutionary War Heroes
American Revolutionary War HeroesAmerican Revolutionary War Heroes
American Revolutionary War Heroes
 

Similar to Grails Spock Testing

Type mock isolator
Type mock isolatorType mock isolator
Type mock isolator
MaslowB
 
Introduction to Unit Testing, BDD and Mocking using TestBox & MockBox at Into...
Introduction to Unit Testing, BDD and Mocking using TestBox & MockBox at Into...Introduction to Unit Testing, BDD and Mocking using TestBox & MockBox at Into...
Introduction to Unit Testing, BDD and Mocking using TestBox & MockBox at Into...
Ortus Solutions, Corp
 

Similar to Grails Spock Testing (20)

Unit Testing
Unit TestingUnit Testing
Unit Testing
 
Unit testing and mocking in Python - PyCon 2018 - Kenya
Unit testing and mocking in Python - PyCon 2018 - KenyaUnit testing and mocking in Python - PyCon 2018 - Kenya
Unit testing and mocking in Python - PyCon 2018 - Kenya
 
Unit testing
Unit testingUnit testing
Unit testing
 
Devday2016 real unittestingwithmockframework-phatvu
Devday2016 real unittestingwithmockframework-phatvuDevday2016 real unittestingwithmockframework-phatvu
Devday2016 real unittestingwithmockframework-phatvu
 
An Introduction to Unit Testing
An Introduction to Unit TestingAn Introduction to Unit Testing
An Introduction to Unit Testing
 
Ch11lect1 ud
Ch11lect1 udCh11lect1 ud
Ch11lect1 ud
 
Testing Angular
Testing AngularTesting Angular
Testing Angular
 
Agile Mumbai 2020 Conference | How to get the best ROI on Your Test Automati...
Agile Mumbai 2020 Conference |  How to get the best ROI on Your Test Automati...Agile Mumbai 2020 Conference |  How to get the best ROI on Your Test Automati...
Agile Mumbai 2020 Conference | How to get the best ROI on Your Test Automati...
 
Microsoft Fakes, Unit Testing the (almost) Untestable Code
Microsoft Fakes, Unit Testing the (almost) Untestable CodeMicrosoft Fakes, Unit Testing the (almost) Untestable Code
Microsoft Fakes, Unit Testing the (almost) Untestable Code
 
Unit Tests with Microsoft Fakes
Unit Tests with Microsoft FakesUnit Tests with Microsoft Fakes
Unit Tests with Microsoft Fakes
 
Beginners overview of automated testing with Rspec
Beginners overview of automated testing with RspecBeginners overview of automated testing with Rspec
Beginners overview of automated testing with Rspec
 
[DevDay 2016] Real Unit Testing with mocking framework - Speaker: Phat Vu – S...
[DevDay 2016] Real Unit Testing with mocking framework - Speaker: Phat Vu – S...[DevDay 2016] Real Unit Testing with mocking framework - Speaker: Phat Vu – S...
[DevDay 2016] Real Unit Testing with mocking framework - Speaker: Phat Vu – S...
 
An Introduction to Unit Testing
An Introduction to Unit TestingAn Introduction to Unit Testing
An Introduction to Unit Testing
 
Episode 5 - Writing unit tests in Salesforce
Episode 5 - Writing unit tests in SalesforceEpisode 5 - Writing unit tests in Salesforce
Episode 5 - Writing unit tests in Salesforce
 
Type mock isolator
Type mock isolatorType mock isolator
Type mock isolator
 
Introduction to Unit Testing, BDD and Mocking using TestBox & MockBox at Into...
Introduction to Unit Testing, BDD and Mocking using TestBox & MockBox at Into...Introduction to Unit Testing, BDD and Mocking using TestBox & MockBox at Into...
Introduction to Unit Testing, BDD and Mocking using TestBox & MockBox at Into...
 
Introduction to Unit Testing, BDD and Mocking using TestBox & MockBox at Adob...
Introduction to Unit Testing, BDD and Mocking using TestBox & MockBox at Adob...Introduction to Unit Testing, BDD and Mocking using TestBox & MockBox at Adob...
Introduction to Unit Testing, BDD and Mocking using TestBox & MockBox at Adob...
 
Test Driven Development - Workshop
Test Driven Development - WorkshopTest Driven Development - Workshop
Test Driven Development - Workshop
 
Codemotion 2015 spock_workshop
Codemotion 2015 spock_workshopCodemotion 2015 spock_workshop
Codemotion 2015 spock_workshop
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 

More from TO THE NEW | Technology

10 Pragmatic UX techniques for building smarter products:
10 Pragmatic UX techniques for building smarter products:10 Pragmatic UX techniques for building smarter products:
10 Pragmatic UX techniques for building smarter products:
TO THE NEW | Technology
 
12 Key points which make Swift more effective than Objective C
12 Key points which make Swift more effective than Objective C12 Key points which make Swift more effective than Objective C
12 Key points which make Swift more effective than Objective C
TO THE NEW | Technology
 
AWS CodeDeploy
AWS CodeDeployAWS CodeDeploy
AWS CodeDeploy
TO THE NEW | Technology
 
MongoDb and NoSQL
MongoDb and NoSQLMongoDb and NoSQL
MongoDb and NoSQL
TO THE NEW | Technology
 
(AWS) Auto Scaling : Evening Session by Amazon and IntelliGrape Software
(AWS) Auto Scaling : Evening Session by Amazon and IntelliGrape Software(AWS) Auto Scaling : Evening Session by Amazon and IntelliGrape Software
(AWS) Auto Scaling : Evening Session by Amazon and IntelliGrape Software
TO THE NEW | Technology
 
BigData Search Simplified with ElasticSearch
BigData Search Simplified with ElasticSearchBigData Search Simplified with ElasticSearch
BigData Search Simplified with ElasticSearch
TO THE NEW | Technology
 
Introduction to Kanban
Introduction to KanbanIntroduction to Kanban
Introduction to Kanban
TO THE NEW | Technology
 

More from TO THE NEW | Technology (20)

10 Best Node.js Practices you Need to Know!
10 Best Node.js Practices you Need to Know!10 Best Node.js Practices you Need to Know!
10 Best Node.js Practices you Need to Know!
 
10 Pragmatic UX techniques for building smarter products:
10 Pragmatic UX techniques for building smarter products:10 Pragmatic UX techniques for building smarter products:
10 Pragmatic UX techniques for building smarter products:
 
12 Key points which make Swift more effective than Objective C
12 Key points which make Swift more effective than Objective C12 Key points which make Swift more effective than Objective C
12 Key points which make Swift more effective than Objective C
 
Gulp - The Streaming Build System
Gulp - The Streaming Build SystemGulp - The Streaming Build System
Gulp - The Streaming Build System
 
Grails Spring Boot
Grails Spring BootGrails Spring Boot
Grails Spring Boot
 
AWS Elastic Beanstalk
AWS Elastic BeanstalkAWS Elastic Beanstalk
AWS Elastic Beanstalk
 
Content migration to AEM
Content migration to AEMContent migration to AEM
Content migration to AEM
 
AWS CodeDeploy
AWS CodeDeployAWS CodeDeploy
AWS CodeDeploy
 
Big Data Expertise
Big Data ExpertiseBig Data Expertise
Big Data Expertise
 
An introduction to Object Oriented JavaScript
An introduction to Object Oriented JavaScriptAn introduction to Object Oriented JavaScript
An introduction to Object Oriented JavaScript
 
Object Oriented JavaScript - II
Object Oriented JavaScript - IIObject Oriented JavaScript - II
Object Oriented JavaScript - II
 
MongoDb and NoSQL
MongoDb and NoSQLMongoDb and NoSQL
MongoDb and NoSQL
 
(AWS) Auto Scaling : Evening Session by Amazon and IntelliGrape Software
(AWS) Auto Scaling : Evening Session by Amazon and IntelliGrape Software(AWS) Auto Scaling : Evening Session by Amazon and IntelliGrape Software
(AWS) Auto Scaling : Evening Session by Amazon and IntelliGrape Software
 
MongoDB using Grails plugin by puneet behl
MongoDB using Grails plugin by puneet behlMongoDB using Grails plugin by puneet behl
MongoDB using Grails plugin by puneet behl
 
Cloud Formation
Cloud FormationCloud Formation
Cloud Formation
 
BigData Search Simplified with ElasticSearch
BigData Search Simplified with ElasticSearchBigData Search Simplified with ElasticSearch
BigData Search Simplified with ElasticSearch
 
JULY IN GRAILS
JULY IN GRAILSJULY IN GRAILS
JULY IN GRAILS
 
Getting groovier-with-vertx
Getting groovier-with-vertxGetting groovier-with-vertx
Getting groovier-with-vertx
 
Introduction to Kanban
Introduction to KanbanIntroduction to Kanban
Introduction to Kanban
 
Introduction to Heroku
Introduction to HerokuIntroduction to Heroku
Introduction to Heroku
 

Recently uploaded

The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 

Recently uploaded (20)

HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 

Grails Spock Testing

  • 1.
  • 3. Agenda 1. Testingoverview 2. Understanding UnitTesting 3. Spock UnitTesting 4. Writing Unit test cases 5. Demo 6. Exercise
  • 4. What do we test ? What a program issupposed to do == What the program actuallydoes
  • 5. Motivation Peopleare not perfect We make errorsin design and code
  • 6. Testing is an Investment Over the time the tests build, the early investment in writingtest cases pays dividends later as the sizeof the application grows
  • 7. A way Of Thinking • Design and Coding are creative while Testing isDestructive • Primarygoal isto break the software • Very often the same person does coding and testing. He needs a splitpersonality • One needs to be paranoid and malicious • Surprisinglyhard to do as people don't like finding themselves making mistakes
  • 8. MailService.groovy • Testing isa process of executing software with the intention of finding errors • Good testing has high probability of finding yet undiscovered errors • Successful testing discoverserrors • Ifit did not, need to ask whether our testing approach isgood or not
  • 9. Integral Part of Development • Testingneedstobe integralpartateach levelof development • Types: • Unit testing (whitebox) • Integration testing (whitebox) • Functional testing (blackbox) • Acceptance testing
  • 10. Understanding Unit testing • Individual units of source code are tested • A unit isthe smallest testable part of the application • Each test case isindependent of the others • Substituteslike mock, stubs areused • Testsindividual methods or blocks without considering the surrounding infrastructure • A unit test provides a strict contract that a piece of code MUSTsatisfy
  • 11. Disadvantages of Unit testing • Test cases ‐written to suit programmer’simplementation(not necessarily specification) • The actual database or external file isnever tested directly • Highly reliant on Refactoring and Programming skils
  • 12. Advantages of Unit testing • Facilitates change • Allows refactoring at a later date and makes sure the module stil workscorrectly • SimplifiesIntegration • Byremoving uncertainty among units themselves • Acts asDocumentation • Acts as a living documentation of a system
  • 13. Advantages of Unit testing • Evolvesdesign • In“Test Driven Approach”, the unit test may take the place of formal design. Each unit test case acts as a design element for classes, methods and behaviour • Improves the Quality Of the Software
  • 14. Spock • A developer testing framework for Java and Groovy application • Based onGroovy • What makes it stand out from the crowd isitsbeautiful and highly expressive specification language
  • 16. import spock.lang.* Package spock.lang contains themostimportanttypesfor writing specifications
  • 17. Specification • A specification isrepresented as a Groovy class that extends from spock.lang.Specification, e.g., • class MyFirstSpecification extends Specification{ • } • Class names of Spock tests must end in either “Spec” or “Specification”. Otherwise the Grails test runner won't find them.
  • 18. … contd • Specification contains a number of useful methods for writing specifications • Instructs JUnit to run specification withSputnik, Spock's JUnitrunner
  • 19. Fields • Declarations: • def obj =newClass() • @Shared res =new VeryExpensiveResource()
  • 20. Fixture Methods • Fixture methods are responsible for setting up and cleaning up the environment in which feature methods are run. • def setup(){} • def cleanup(){} • def setupSpec(){} • def cleanupSpec() {}
  • 21. Blocks • A test case can have following blocks: • setup • when //forstimulus • then //output comparison • expect • where
  • 23. Expect Block • Itisuseful in situations where itis more natural to describestimulus and expected response in a singleexpression
  • 24. Where block • Itisused to write data-driven featuremethods
  • 25. Data Driven Testing • Itisuseful to exercise the same test code multiple times, with varying inputs and expected results. • Itisa firstclass feature in Spock
  • 26. Data Tables • A convenient way to exercise a feature method with a fixed set of data
  • 27. Data Pipes • A data pipe, indicated by the left-shift (<<)operator, connects a data variable to a data provider.
  • 28. @Unroll • A method annotated with @Unrol will have itsiterations reported independently
  • 29. Exception Conditions • They are used to describe that a when block should throw an exception
  • 30. Mocking • Mock objects literally implement (or extend) the type they stand in for • Initiallymock objects have no behavior • Calling methods on them is allowed but has no effect otherthan returning the default value for the method’s return type, except for equals and toString • A mock object isonly equal to itself, has a unique hash code, and a string representation that includes the name of the type it represents
  • 31. ..contd. • Thisdefault behavior isoverrideable by stubbing the methods • Mock objects are created with the MockingApi.Mock() • def subscriber =Mock(Subscriber) • Subscriber subsriber =Mock()
  • 32. mockDomain() • Takesa class and mock implementations of all the domain class methods accessible onit • mockDomain() provides a versionof domain classes in which the database issimply listof domain instances in memory. • mockDomain(Person, [persons]) • All mocked methods like save(),get() etc work against thislist.
  • 33. mockForConstraintsTest() • Highly specialized mocking for domain classes and command objects that allows you to check whether the constraints are behaving as expectedor not • Itsimply adds a validate() method to a given domain class. • mockForConstraintsTests(Person, [persons])
  • 34. Test Mixins • Since Grails 2.0,a collection of unit testing mixinsisprovided by Grails, that enhances the behavior of a typical Junit or Spock test • Common examplesare: • @TestFor(BookController) • @Mock([Book,Author])
  • 35. TestFor Annotation • The TestFor annotation defines a class under test and will automatically create a field for the type of class under test • For example, @TestFor(BookController) this will automaticallycreate “controller” field • IfTestForwas defined for a service then a “service” field would be created
  • 36. Mock Annotation • The Mock annotation creates a mock version of any collaborators • There isan in-memory implementation of GORM that will simulate most interactions with GORM API • For those interactions that are not automatically mocked, you need to define mocksprogrammatically
  • 37. Cardinality • The cardinality of an interaction describes how often a method call is expected. Itcan either be a fixed number or a range • 1 *subscriber.receive(“hello”) • 0..1)*subscriber.receive(“hello”) • 0.._)*subscriber.receive(“hello”) • 1 *subscriber._(“hello”)
  • 39. Stubbing • Stubbing isthe act of making collaborators respond to method calls in acertain way • Inother words stubbing isjustproviding dummy implementation of a method
  • 40. Stubbing Examples • Returning FixedValues: • subscriber.receive(_)>>”Ok” • Toreturn different values on successive invocations, use the triple- right-shift(>>>)operator • subscriber.receive(_) >>>["ok","error","error", "ok"]
  • 41. ...contd. • Accessing Method Arguments • subscriber.receive(_) >>{String message ->message.size() >3 ? "ok":"fail"} • Throw anexception: • subscriber.receive(_) >>{throw new InternalError("ouch")}
  • 42. Test Code Coverage Plugin • Creates test code coverage for your code • Add dependency: • test ":code-coverage:1.2.6" • Torun: • grails test-app -coverage • The script will create HTLMreports and place them in the tests/report/cobertura directory.
  • 43. References • https://code.google.com/p/spock/wiki/SpockBasics • https://code.google.com/p/spock/wiki/GettingStarted • http://docs.spockframework.org/en/latest/ • http://meetspock.appspot.com/ • http://naleid.com/blog/2012/05/01/upgrading-to-grails-2-unit- testing/
  • 44. Contact us Our Office Client Location Click Here To Know More! Have more queries on Grails? Talk to our GRAILS experts Now! Talk To Our Experts Here's how the world's biggest Grails team is building enterprise applications on Grails!