SlideShare a Scribd company logo
UnitTesting
Using SPOCK
Agenda
Testing
Unit Testing
Spock Unit Testing
Unit Test Cases
Demo
Practice
TestinG
Testing is to check the equality of “What program supposed to
do” and “what actually program does”.
Program supposed to do == Program actually does
whyweneedtesting
We are not perfect, usually we do errors in coding and
design.
We have some wrong perception about Testing:-
Designing and Coding is a creation, but testing is
destruction.
We don’t like finding ourselves making mistake, so avoid
testing.
It’s primary goal to break the software.
Whattestingdoes
It is process of executing software with the intention of
finding errors.
It can help us to find undiscovered errors.
Typeoftesting
Unit Testing
Integration Testing
Functional Testing
Unittesting
Individual unit (function or method) of source code are
tested.
It is the smallest testable part of application.
Each test case will be independent of others.
Substitutes like mock and stubs are used.
Prosandconsof Unittesting
Pros:-
Allows refactoring at a later date and ensures module still
works.
Acts as a living documentation of system.
Improves the quality of software.
Cons:-
Actual database and external files never tested directly.
Highly reliant on refactoring and Programming Skills.
Spock
A developer testing framework for Java and Groovy
application.
Based on Groovy.
Spock lets us to write specifications that describe expected
features.
Howtointegratespock
import spock.lang.*;
Package spock.lang contains the most important types for
writing specifications.
Need not to integrate spock after grails 2.3.*
dependency{
test "org.spockframework:spock-grails-support:0.7-groovy-2.0"
}
plugins{
test(":spock:0.7") {
exclude "spock-grails-support"
}
}
Specifications
A specification is represented as a Groovy class that extends
from spock.lang.Specification.
class FirstTestingSpecification extends Specification{}
Class names of Spock tests must end in either “Spec” or
“Specification”. Otherwise the grails test runner won’t find
them.
It contains a number of useful methods (fixture methods) for
writing specifications
FixtureMethods
Fixture methods are responsible for setting up and cleaning
up the environment in which feature methods are run
def setup() //run before every feature method
def cleanup() //run after every feature method
def setupSpec() //run before the first feature method
def cleanupSpec() //run after the last feature method
Feature Method:- def “pushing a new element in the stack”(){}
Blocks
A test can have following blocks:-
setup
when //for the stimulus
then //output comparison
expect
where
Example
when:
stack.push(elem)
then:
!stack.empty
stack.size()>0
stack.peek()=elem
Expectblock
It is more natural to describe stimulus and expected response
in a single expression:-
when:
def x=Math.max(1,2)
then:
x==2
expect:
Math.max(1,2)==2
It is useful to test same code multiple times, with varying
inputs and expected result.
Data-driventesting
class MathSpec extends Specification{
def “maximum of two number”(){
expect:
Math.max(1,2)==2
Math.max(10,9) ==10
Math.max(0,0) ==0
}
}
class MathSpec extends Specification{
def “maximum of two number”(int a, int
b, int c){
expect:
Math.max(a,b)==c
}
}
Data-Table
A convenient way to exercise a feature method with a fixed
set of data.
class DataDrivenSpec extends Specificaition{
def “max of two num”(){
expect:
Math.max(a,b)==c
where:
a|b|c
3|5|5
7|0|7
0|0|0
}
}
Data-pipe
A data-pipe, indicated by left shift(<<)
where:
a<<[3, 7, 0]
b<<[5, 0, 0]
c<<[5, 7, 0]
@Unroll
A method annoted with @unroll will have its iterations
reported independently
@Unroll
def “max of two num”(){
…
}
@Unroll “#a and #b and result is #c”
ExceptionCondition
setup:
Stack stack=new Stack()
when:
stack.pop()
then:
thrown(EmptyStackException)
stack.empty
mocking
A mock is an object of certain type but without any
behaviour.
Calling methods on them is allowed, but have no effects other
than returning the default value for the method’s return
type.
Mock objects are creatd by:-
def tester = Mock(tester)
Tester tester = Mock()
MockingMethods
mockDomain()
Mock()
mockConfig()
mockLogging()
mockDomain
Adds the persistence method:-
get(), getAll(), exists(), count(), list(),create(), save(),
validate(), delete(), discard(), addTo(), removeFrom().
mockDomain(MyDomain, [])
MyDomain object = new MyDomain(name:”Vijay”)
object.save()
Mock
It can be used to mock any of the class.
Return an Object of the class.
MyService service = Mock()
service.anyMethod(a, b)>>result
Testmixins
Since grails 2.0, a collection of unit testing mixins is
provided.
e.g.,
@TestFor(COntroller_Name) @IgnoreRest
@Mock([domain1, domain2]) @FailsWith
@Timeout
@Ignore
Testfor
It defines a class under the test and automatically create a
field for the type of class.
e.g., @TestFor(BookController) this will create “controller”
field.
@TestFor(BookService) this will create “service” field.
Stubbing
Stubbing is just providing the dummy implementation of any
method. e.g.,
Return fixed value:-
service.findName(_)>>”Nexthoughts”
Return different values:-
service.findName(_)>>>[“Credio”, “Investly”, “TransferGuru”]
Accessing Method Argument:-
service.findName(_) >>{String name->
name.lenght()>0?name:”error”
}
Throw an Exception:-
service.findName(_) >>{throw new InternalError(“Got You!”)}
Questions
References
http://grails.github.io/grails-doc/3.0.x/guide/testing.html
http://docs.groovy-
lang.org/docs/latest/html/documentation/core-testing-
guide.html
http://www.slideshare.net/pleeps/grails-unit-testing
http://grails.github.io/grails-
doc/2.3.4/guide/upgradingFromPreviousVersionsOfGrails.html
BasicCommands
grails [Environment]* test-app [names]*
grails test-app <file-name>
You can run different test like:-
grails test-app -unit (For Unit Testing)
grails test-app -integration (For Integration Testing)
If you want to run only failed test cases:-
grails test-app -rerun
To open your test-report
open test-report
To run only Controller
grails test-app *Controller
ThankYou
Presented By:- Vijay Shukla

More Related Content

PDF
Unit test-using-spock in Grails
NexThoughts Technologies
 
PPTX
Grails Spock Testing
TO THE NEW | Technology
 
ODP
Grails unit testing
pleeps
 
PDF
JUnit & Mockito, first steps
Renato Primavera
 
PPTX
Power mock
Piyush Mittal
 
PPT
Junit and testNG
Марія Русин
 
PPT
testng
harithakannan
 
PDF
All about unit testing using (power) mock
Pranalee Rokde
 
Unit test-using-spock in Grails
NexThoughts Technologies
 
Grails Spock Testing
TO THE NEW | Technology
 
Grails unit testing
pleeps
 
JUnit & Mockito, first steps
Renato Primavera
 
Power mock
Piyush Mittal
 
Junit and testNG
Марія Русин
 
All about unit testing using (power) mock
Pranalee Rokde
 

What's hot (20)

PDF
TestNG vs. JUnit4
Andrey Oleynik
 
PPSX
Junit
FAROOK Samath
 
PPT
Mockito with a hint of PowerMock
Ying Zhang
 
PDF
Mocking in Java with Mockito
Richard Paul
 
PPTX
Unit Testing with JUnit4 by Ravikiran Janardhana
Ravikiran J
 
PPTX
Unit Testing in Java
Ahmed M. Gomaa
 
PPT
xUnit Style Database Testing
Chris Oldwood
 
PDF
JUnit 5
Scott Leberknight
 
PPTX
TestNG vs JUnit: cease fire or the end of the war
Oleksiy Rezchykov
 
PPTX
TestNG vs Junit
Büşra İçöz
 
PPTX
Introduction to JUnit
Devvrat Shukla
 
PDF
An introduction to Google test framework
Abner Chih Yi Huang
 
PPTX
Junit4&testng presentation
Sanjib Dhar
 
PPTX
Test ng
Ramakrishna kapa
 
PDF
JUnit Pioneer
Scott Leberknight
 
PDF
TestNG introduction
Denis Bazhin
 
PPTX
Test ng tutorial
Srikrishna k
 
PPTX
TestNG Framework
Levon Apreyan
 
PPT
Unit testing with java
Dinuka Malalanayake
 
TestNG vs. JUnit4
Andrey Oleynik
 
Mockito with a hint of PowerMock
Ying Zhang
 
Mocking in Java with Mockito
Richard Paul
 
Unit Testing with JUnit4 by Ravikiran Janardhana
Ravikiran J
 
Unit Testing in Java
Ahmed M. Gomaa
 
xUnit Style Database Testing
Chris Oldwood
 
TestNG vs JUnit: cease fire or the end of the war
Oleksiy Rezchykov
 
TestNG vs Junit
Büşra İçöz
 
Introduction to JUnit
Devvrat Shukla
 
An introduction to Google test framework
Abner Chih Yi Huang
 
Junit4&testng presentation
Sanjib Dhar
 
JUnit Pioneer
Scott Leberknight
 
TestNG introduction
Denis Bazhin
 
Test ng tutorial
Srikrishna k
 
TestNG Framework
Levon Apreyan
 
Unit testing with java
Dinuka Malalanayake
 
Ad

Viewers also liked (20)

PPT
Grails Plugins
NexThoughts Technologies
 
PPTX
Grails Services
NexThoughts Technologies
 
PPTX
Config BuildConfig
NexThoughts Technologies
 
PPT
Linux Introduction
NexThoughts Technologies
 
PPT
Grails Views
NexThoughts Technologies
 
PPT
Introduction to Grails
NexThoughts Technologies
 
ODP
Groovy intro
NexThoughts Technologies
 
PPTX
Meta Programming in Groovy
NexThoughts Technologies
 
PPTX
Introduction to mongo db
NexThoughts Technologies
 
PPTX
Grails Plugins(Console, DB Migration, Asset Pipeline and Remote pagination)
NexThoughts Technologies
 
PPTX
MetaProgramming with Groovy
NexThoughts Technologies
 
PPTX
Actors model in gpars
NexThoughts Technologies
 
PPTX
Java reflection
NexThoughts Technologies
 
PPT
Grails Controllers
NexThoughts Technologies
 
PPTX
Grails services
NexThoughts Technologies
 
Grails Plugins
NexThoughts Technologies
 
Grails Services
NexThoughts Technologies
 
Config BuildConfig
NexThoughts Technologies
 
Linux Introduction
NexThoughts Technologies
 
Introduction to Grails
NexThoughts Technologies
 
Meta Programming in Groovy
NexThoughts Technologies
 
Introduction to mongo db
NexThoughts Technologies
 
Grails Plugins(Console, DB Migration, Asset Pipeline and Remote pagination)
NexThoughts Technologies
 
MetaProgramming with Groovy
NexThoughts Technologies
 
Actors model in gpars
NexThoughts Technologies
 
Java reflection
NexThoughts Technologies
 
Grails Controllers
NexThoughts Technologies
 
Grails services
NexThoughts Technologies
 
Ad

Similar to Unit testing (20)

PPTX
In search of JavaScript code quality: unit testing
Anna Khabibullina
 
ODP
Good Practices On Test Automation
Gustavo Labbate Godoy
 
PDF
Unit testing - A&BP CC
JWORKS powered by Ordina
 
PDF
Spock: Test Well and Prosper
Ken Kousen
 
ODP
Easymock Tutorial
Sbin m
 
PPTX
Unit/Integration Testing using Spock
Anuj Aneja
 
PDF
Effective testing with pytest
Hector Canto
 
PDF
How to fake_properly
Rainer Schuettengruber
 
PPT
Testing And Drupal
Peter Arato
 
PPT
Spock
Gajraj Kalburgi
 
PDF
Android testing
Sean Tsai
 
PPTX
Python mocking intro
Hans Jones
 
PDF
Token Testing Slides
ericholscher
 
PPTX
Junit_.pptx
Suman Sourav
 
PPTX
8-testing.pptx
ssuserd0fdaa
 
PPTX
Easy mock
Ramakrishna kapa
 
PDF
We Are All Testers Now: The Testing Pyramid and Front-End Development
All Things Open
 
PDF
Unit Testing on Android - Droidcon Berlin 2015
Buşra Deniz, CSM
 
PDF
Тестирование и Django
MoscowDjango
 
PPT
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
Lohika_Odessa_TechTalks
 
In search of JavaScript code quality: unit testing
Anna Khabibullina
 
Good Practices On Test Automation
Gustavo Labbate Godoy
 
Unit testing - A&BP CC
JWORKS powered by Ordina
 
Spock: Test Well and Prosper
Ken Kousen
 
Easymock Tutorial
Sbin m
 
Unit/Integration Testing using Spock
Anuj Aneja
 
Effective testing with pytest
Hector Canto
 
How to fake_properly
Rainer Schuettengruber
 
Testing And Drupal
Peter Arato
 
Android testing
Sean Tsai
 
Python mocking intro
Hans Jones
 
Token Testing Slides
ericholscher
 
Junit_.pptx
Suman Sourav
 
8-testing.pptx
ssuserd0fdaa
 
Easy mock
Ramakrishna kapa
 
We Are All Testers Now: The Testing Pyramid and Front-End Development
All Things Open
 
Unit Testing on Android - Droidcon Berlin 2015
Buşra Deniz, CSM
 
Тестирование и Django
MoscowDjango
 
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
Lohika_Odessa_TechTalks
 

More from NexThoughts Technologies (20)

PDF
Alexa skill
NexThoughts Technologies
 
PDF
Docker & kubernetes
NexThoughts Technologies
 
PDF
Apache commons
NexThoughts Technologies
 
PDF
Microservice Architecture using Spring Boot with React & Redux
NexThoughts Technologies
 
PDF
Solid Principles
NexThoughts Technologies
 
PDF
Introduction to TypeScript
NexThoughts Technologies
 
PDF
Smart Contract samples
NexThoughts Technologies
 
PDF
My Doc of geth
NexThoughts Technologies
 
PDF
Geth important commands
NexThoughts Technologies
 
PDF
Ethereum genesis
NexThoughts Technologies
 
PPTX
Springboot Microservices
NexThoughts Technologies
 
PDF
An Introduction to Redux
NexThoughts Technologies
 
PPTX
Google authentication
NexThoughts Technologies
 
Docker & kubernetes
NexThoughts Technologies
 
Apache commons
NexThoughts Technologies
 
Microservice Architecture using Spring Boot with React & Redux
NexThoughts Technologies
 
Solid Principles
NexThoughts Technologies
 
Introduction to TypeScript
NexThoughts Technologies
 
Smart Contract samples
NexThoughts Technologies
 
My Doc of geth
NexThoughts Technologies
 
Geth important commands
NexThoughts Technologies
 
Ethereum genesis
NexThoughts Technologies
 
Springboot Microservices
NexThoughts Technologies
 
An Introduction to Redux
NexThoughts Technologies
 
Google authentication
NexThoughts Technologies
 

Recently uploaded (20)

PDF
An Experience-Based Look at AI Lead Generation Pricing, Features & B2B Results
Thomas albart
 
PDF
49785682629390197565_LRN3014_Migrating_the_Beast.pdf
Abilash868456
 
PPTX
ConcordeApp: Engineering Global Impact & Unlocking Billions in Event ROI with AI
chastechaste14
 
PDF
ChatPharo: an Open Architecture for Understanding How to Talk Live to LLMs
ESUG
 
PDF
Download iTop VPN Free 6.1.0.5882 Crack Full Activated Pre Latest 2025
imang66g
 
PDF
Applitools Platform Pulse: What's New and What's Coming - July 2025
Applitools
 
PPTX
Web Testing.pptx528278vshbuqffqhhqiwnwuq
studylike474
 
PDF
Salesforce Implementation Services Provider.pdf
VALiNTRY360
 
PDF
What to consider before purchasing Microsoft 365 Business Premium_PDF.pdf
Q-Advise
 
PPTX
classification of computer and basic part of digital computer
ravisinghrajpurohit3
 
PDF
On Software Engineers' Productivity - Beyond Misleading Metrics
Romén Rodríguez-Gil
 
PPTX
Presentation about Database and Database Administrator
abhishekchauhan86963
 
DOCX
Can You Build Dashboards Using Open Source Visualization Tool.docx
Varsha Nayak
 
PDF
lesson-2-rules-of-netiquette.pdf.bshhsjdj
jasmenrojas249
 
PDF
New Download FL Studio Crack Full Version [Latest 2025]
imang66g
 
PDF
Key Features to Look for in Arizona App Development Services
Net-Craft.com
 
PPTX
TRAVEL APIs | WHITE LABEL TRAVEL API | TOP TRAVEL APIs
philipnathen82
 
PPTX
Visualising Data with Scatterplots in IBM SPSS Statistics.pptx
Version 1 Analytics
 
PPTX
ASSIGNMENT_1[1][1][1][1][1] (1) variables.pptx
kr2589474
 
PDF
vAdobe Premiere Pro 2025 (v25.2.3.004) Crack Pre-Activated Latest
imang66g
 
An Experience-Based Look at AI Lead Generation Pricing, Features & B2B Results
Thomas albart
 
49785682629390197565_LRN3014_Migrating_the_Beast.pdf
Abilash868456
 
ConcordeApp: Engineering Global Impact & Unlocking Billions in Event ROI with AI
chastechaste14
 
ChatPharo: an Open Architecture for Understanding How to Talk Live to LLMs
ESUG
 
Download iTop VPN Free 6.1.0.5882 Crack Full Activated Pre Latest 2025
imang66g
 
Applitools Platform Pulse: What's New and What's Coming - July 2025
Applitools
 
Web Testing.pptx528278vshbuqffqhhqiwnwuq
studylike474
 
Salesforce Implementation Services Provider.pdf
VALiNTRY360
 
What to consider before purchasing Microsoft 365 Business Premium_PDF.pdf
Q-Advise
 
classification of computer and basic part of digital computer
ravisinghrajpurohit3
 
On Software Engineers' Productivity - Beyond Misleading Metrics
Romén Rodríguez-Gil
 
Presentation about Database and Database Administrator
abhishekchauhan86963
 
Can You Build Dashboards Using Open Source Visualization Tool.docx
Varsha Nayak
 
lesson-2-rules-of-netiquette.pdf.bshhsjdj
jasmenrojas249
 
New Download FL Studio Crack Full Version [Latest 2025]
imang66g
 
Key Features to Look for in Arizona App Development Services
Net-Craft.com
 
TRAVEL APIs | WHITE LABEL TRAVEL API | TOP TRAVEL APIs
philipnathen82
 
Visualising Data with Scatterplots in IBM SPSS Statistics.pptx
Version 1 Analytics
 
ASSIGNMENT_1[1][1][1][1][1] (1) variables.pptx
kr2589474
 
vAdobe Premiere Pro 2025 (v25.2.3.004) Crack Pre-Activated Latest
imang66g
 

Unit testing

Editor's Notes

  • #10: Created in 2008 By Peter Niederwieser