0
GRAILS SPOCK TESTING
Puneet Kaur
Agenda
 Testing overview
 Understanding Unit Testing
 Spock Unit Testing
 Writing Unit test cases
 Demo
 Exercise
What do we test ?
What a program is supposed to do
==
What the program actually does
Motivation
People are not perfect
We make errors in design and code
Testing is an Investment
Over the time the tests
build, the early investment in
writing test cases pays
dividends later as...
A way Of Thinking
 Design and Coding are creative while Testing is
Destructive
 Primary goal is to break the software
 ...
Testing
 Testing is a process of executing software with the
intention of finding errors
 Good testing has high probabil...
Integral Part of Development
 Testing needs to be integral part at each level of
development.
 Types:
 Unit testing (wh...
Understanding Unit testing
 Individual units of source code are tested
 A unit is the smallest testable part of the appl...
Disadvantages of Unit testing
 Test cases ‐written to suit programmer’s implementation
(not necessarily specification)
 ...
Advantages of Unit testing
 Facilitates change
 Allows refactoring at a later date and makes
sure the module still works...
Advantages of Unit testing
 Evolves design
 In “Test Driven Approach”, the unit test may
take the place of formal design...
Spock
 A developer testing framework for Java and Groovy
application
 Based on Groovy
 What makes it stand out from the...
Basics
Spock lets you write specifications that describe expected
features (properties, aspects) exhibited by a system of
...
import spock.lang.*
Package spock.lang contains the most important types
for writing specifications
Specification
 A specification is represented as a Groovy class that
extends from spock.lang.Specification, e.g.,
class M...
… contd
 Specification contains a number of useful methods for
writing specifications
 Instructs JUnit to run specificat...
Fields
 Declarations:
def obj = new Class()
@Shared res = new
VeryExpensiveResource()
Fixture Methods
 Fixture methods are responsible for setting up and
cleaning up the environment in which feature methods
...
Blocks
 A test case can have following blocks:
 setup
 when //for stimulus
 then //output comparison
 expect
 where
Example
Expect Block
 It is useful in situations
where it is more natural to
describe stimulus and
expected response in a
single ...
Where block
• It is used to write data-driven feature methods
Data Driven Testing
 It is useful to exercise the same test code multiple
times, with varying inputs and expected results...
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
@Unroll will have its
iterations 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
 Initially mock objects have no behavio...
..contd.
 This default behavior is overrideable by stubbing the
methods
 Mock objects are created with the
MockingApi.Mo...
mockDomain()
 Takes a class and mock implementations of all the
domain class methods accessible on it.
 mockDomain() pro...
mockForConstraintsTest()
 Highly specialized mocking for domain classes and
command objects that allows you to check whet...
Test Mixins
 Since Grails 2.0, a collection of unit testing mixins is
provided by Grails, that enhances the behavior of a...
TestFor Annotation
 The TestFor annotation defines a class under test and
will automatically create a field for the type ...
Mock Annotation
 The Mock annotation creates a mock version of any
collaborators
 There is an in-memory implementation o...
Cardinality
 The cardinality of an interaction describes how often a
method call is expected. It can either be a fixed nu...
Verification Of Interactions
Stubbing
 Stubbing is the act of making collaborators respond to
method calls in a certain way.
 In other words stubbing...
Stubbing Examples
 Returning Fixed Values:
 subscriber.receive(_)>>”Ok”
 To return different values on successive invoc...
...contd.
 Accessing Method Arguments
 subscriber.receive(_) >> { String
message -> message.size() > 3 ?
"ok" : "fail" }...
Test Code Coverage Plugin
 Creates test code coverage for your code
 Add dependency:
 test ":code-coverage:1.2.6"
 To ...
References
 https://code.google.com/p/spock/wiki/SpockBasics
 https://code.google.com/p/spock/wiki/GettingStarted
 http...
Let’s Connect
IntelliGrape Software (P) Ltd
SDF L-6, NSEZ,
NOIDA Phase 2,
U.P. , India
Phone : +91-120-6493668
Fax : +91-1...
Upcoming SlideShare
Loading in...5
×

Grails Spock Testing | Intelligrape

4,844

Published on

INtelligrape Provides agile tsolution to programming quesries. With its team of experienced software programmers, we are capablle of working on various languages.
Spock testing gives you the option of testing your grails application with accurate results.

Published in: Education, Technology

Transcript of "Grails Spock Testing | Intelligrape"

  1. 1. GRAILS SPOCK TESTING Puneet Kaur
  2. 2. Agenda  Testing overview  Understanding Unit Testing  Spock Unit Testing  Writing Unit test cases  Demo  Exercise
  3. 3. What do we test ? What a program is supposed to do == What the program actually does
  4. 4. Motivation People are not perfect We make errors in design and code
  5. 5. Testing is an Investment Over the time the tests build, the early investment in writing test cases pays dividends later as the size of the application grows.
  6. 6. A way Of Thinking  Design and Coding are creative while Testing is Destructive  Primary goal is to break the software  Very often the same person does coding and testing. He needs a split personality  One needs to be paranoid and malicious  Surprisingly hard to do as people don't like finding themselves making mistakes
  7. 7. Testing  Testing is a process of executing software with the intention of finding errors  Good testing has high probability of finding yet undiscovered errors  Successful testing discovers errors  If it did not, need to ask whether our testing approach is good or not
  8. 8. Integral Part of Development  Testing needs to be integral part at each level of development.  Types:  Unit testing (white box)  Integration testing (white box)  Functional testing (black box)  Acceptance testing
  9. 9. Understanding Unit testing  Individual units of source code are tested  A unit is the smallest testable part of the application  Each test case is independent of the others  Substitutes like mock, stubs are used  Tests individual methods or blocks without considering the surrounding infrastructure  A unit test provides a strict contract that a piece of code MUST satisfy
  10. 10. Disadvantages of Unit testing  Test cases ‐written to suit programmer’s implementation (not necessarily specification)  The actual database or external file is never tested directly  Highly reliant on Refactoring and Programming skills
  11. 11. Advantages of Unit testing  Facilitates change  Allows refactoring at a later date and makes sure the module still works correctly  Simplifies Integration  By removing uncertainty among units themselves  Acts as Documentation  Acts as a living documentation of a system
  12. 12. Advantages of Unit testing  Evolves design  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
  13. 13. Spock  A developer testing framework for Java and Groovy application  Based on Groovy  What makes it stand out from the crowd is its beautiful and highly expressive specification language
  14. 14. Basics Spock lets you write specifications that describe expected features (properties, aspects) exhibited by a system of interest
  15. 15. import spock.lang.* Package spock.lang contains the most important types for writing specifications
  16. 16. Specification  A specification is represented 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.
  17. 17. … contd  Specification contains a number of useful methods for writing specifications  Instructs JUnit to run specification withSputnik, Spock's JUnit runner
  18. 18. Fields  Declarations: def obj = new Class() @Shared res = new VeryExpensiveResource()
  19. 19. 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() {}
  20. 20. Blocks  A test case can have following blocks:  setup  when //for stimulus  then //output comparison  expect  where
  21. 21. Example
  22. 22. Expect Block  It is useful in situations where it is more natural to describe stimulus and expected response in a single expression
  23. 23. Where block • It is used to write data-driven feature methods
  24. 24. Data Driven Testing  It is useful to exercise the same test code multiple times, with varying inputs and expected results.  It is a first class feature in Spock
  25. 25. Data Tables • A convenient way to exercise a feature method with a fixed set of data
  26. 26. Data Pipes • A data pipe, indicated by the left-shift (<<) operator, connects a data variable to a data provider
  27. 27. @Unroll • A method annotated with @Unroll will have its iterations reported independently
  28. 28. Exception Conditions • They are used to describe that a when block should throw an exception
  29. 29. Mocking  Mock objects literally implement (or extend) the type they stand in for  Initially mock objects have no behavior  Calling methods on them is allowed but has no effect other than returning the default value for the method’s return type, except for equals and toString  A mock object is only equal to itself, has a unique hash code, and a string representation that includes the name of the type it represents
  30. 30. ..contd.  This default behavior is overrideable by stubbing the methods  Mock objects are created with the MockingApi.Mock()  def subscriber = Mock(Subscriber)  Subscriber subsriber = Mock()
  31. 31. mockDomain()  Takes a class and mock implementations of all the domain class methods accessible on it.  mockDomain() provides a version of domain classes in which the database is simply list of domain instances in memory.  mockDomain(Person, [persons])  All mocked methods like save(),get() etc work against this list.
  32. 32. mockForConstraintsTest()  Highly specialized mocking for domain classes and command objects that allows you to check whether the constraints are behaving as expected or not.  It simply adds a validate() method to a given domain class.  mockForConstraintsTests(Person, [persons])
  33. 33. Test Mixins  Since Grails 2.0, a collection of unit testing mixins is provided by Grails, that enhances the behavior of a typical Junit or Spock test  Common examples are:  @TestFor(BookController)  @Mock([Book,Author])
  34. 34. 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 automatically create “controller” field.  If TestFor was defined for a service then a “service” field would be created.
  35. 35. Mock Annotation  The Mock annotation creates a mock version of any collaborators  There is an 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 mocks programmatically
  36. 36. Cardinality  The cardinality of an interaction describes how often a method call is expected. It can either be a fixed number or a range  1 * subscriber.receive(“hello”)  0..1) * subscriber.receive(“hello”)  0.._) * subscriber.receive(“hello”)  1 * subscriber._(“hello”)
  37. 37. Verification Of Interactions
  38. 38. Stubbing  Stubbing is the act of making collaborators respond to method calls in a certain way.  In other words stubbing is just providing dummy implementation of a method.
  39. 39. Stubbing Examples  Returning Fixed Values:  subscriber.receive(_)>>”Ok”  To return different values on successive invocations, use the triple-right-shift (>>>) operator  subscriber.receive(_) >>> ["ok", "error", "error", "ok"]
  40. 40. ...contd.  Accessing Method Arguments  subscriber.receive(_) >> { String message -> message.size() > 3 ? "ok" : "fail" }  Throw an exception:  subscriber.receive(_) >> { throw new InternalError("ouch") }
  41. 41. Test Code Coverage Plugin  Creates test code coverage for your code  Add dependency:  test ":code-coverage:1.2.6"  To run:  grails test-app -coverage  The script will create HTLM reports and place them in the tests/report/cobertura directory.
  42. 42. 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/
  43. 43. Let’s Connect IntelliGrape Software (P) Ltd SDF L-6, NSEZ, NOIDA Phase 2, U.P. , India Phone : +91-120-6493668 Fax : +91-120-4207689 Email : query@intelligrape.com
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×