Unit Testing
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
why we need testing
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.
What testing does
It is process of executing software with the intention of finding errors.
It can help us to find undiscovered errors.
Type of testing
Unit Testing
Integration Testing
Functional Testing
Unit testing
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.
Pros and cons of Unit testing
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.
Howto integrate spock
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
Fixture Methods
Fixture methods are responsible for setting up and cleaning up the environment in whic
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
Expect block
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-driven testing
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”
Exception Condition
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 defaul
value for the method’s return type.
Mock objects are creatd by:-
def tester = Mock(tester)
Tester tester = Mock()
Mocking Methods
mockDomain()
Mock()
mockConfig()
mockLogging()
mockDomain
Adds the persistence method:-
get(), getAll(), exists(), count(), list(),create(), save(), validate(), delete(), discard(), add
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
Test mixins
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
Basic Commands
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
Thank You
Presented By:- Vijay Shukla

Unit test-using-spock in Grails

  • 1.
  • 2.
    Agenda Testing Unit Testing Spock UnitTesting Unit Test Cases Demo Practice
  • 3.
    TestinG Testing is tocheck the equality of “What program supposed to do” and “what actually program does”. Program supposed to do == Program actually does
  • 4.
    why we needtesting 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.
  • 5.
    What testing does Itis process of executing software with the intention of finding errors. It can help us to find undiscovered errors.
  • 6.
    Type of testing UnitTesting Integration Testing Functional Testing
  • 7.
    Unit testing 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.
  • 8.
    Pros and consof Unit testing 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.
  • 9.
    Spock A developer testingframework for Java and Groovy application. Based on Groovy. Spock lets us to write specifications that describe expected features.
  • 10.
    Howto integrate spock importspock.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" } }
  • 11.
    Specifications A specification isrepresented 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
  • 12.
    Fixture Methods Fixture methodsare responsible for setting up and cleaning up the environment in whic 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”(){}
  • 13.
    Blocks A test canhave following blocks:- setup when //for the stimulus then //output comparison expect where
  • 14.
  • 15.
    Expect block It ismore 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
  • 16.
    It is usefulto test same code multiple times, with varying inputs and expected result. Data-driven testing 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 } }
  • 17.
    Data-Table A convenient wayto 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 } }
  • 18.
    Data-pipe A data-pipe, indicatedby left shift(<<) where: a<<[3, 7, 0] b<<[5, 0, 0] c<<[5, 7, 0]
  • 19.
    @Unroll A method annotedwith @unroll will have its iterations reported independently @Unroll def “max of two num”(){ … } @Unroll “#a and #b and result is #c”
  • 20.
    Exception Condition setup: Stack stack=newStack() when: stack.pop() then: thrown(EmptyStackException) stack.empty
  • 21.
    mocking A mock isan object of certain type but without any behaviour. Calling methods on them is allowed, but have no effects other than returning the defaul value for the method’s return type. Mock objects are creatd by:- def tester = Mock(tester) Tester tester = Mock()
  • 22.
  • 23.
    mockDomain Adds the persistencemethod:- get(), getAll(), exists(), count(), list(),create(), save(), validate(), delete(), discard(), add removeFrom(). mockDomain(MyDomain, []) MyDomain object = new MyDomain(name:”Vijay”) object.save()
  • 24.
    Mock It can beused to mock any of the class. Return an Object of the class. MyService service = Mock() service.anyMethod(a, b)>>result
  • 25.
    Test mixins Since grails2.0, a collection of unit testing mixins is provided. e.g., @TestFor(COntroller_Name) @IgnoreRest @Mock([domain1, domain2]) @FailsWith @Timeout @Ignore
  • 26.
    Testfor It defines aclass 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.
  • 27.
    Stubbing Stubbing is justproviding 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!”)}
  • 28.
  • 29.
  • 30.
    Basic Commands 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
  • 31.