Your SlideShare is downloading. ×
Grails Spock Testing | Intelligrape
Upcoming SlideShare
Loading in...5

Thanks for flagging this SlideShare!

Oops! An error has occurred.

Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

Grails Spock Testing | Intelligrape


Published on

INtelligrape Provides agile tsolution to programming quesries. With its team of experienced software programmers, we are capablle of working on various languages. …

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

  • Be the first to comment

No Downloads
Total Views
On Slideshare
From Embeds
Number of Embeds
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

No notes for slide


  • 2. Agenda  Testing overview  Understanding Unit Testing  Spock Unit Testing  Writing Unit test cases  Demo  Exercise
  • 3. What do we test ? What a program is supposed to do == What the program actually does
  • 4. Motivation People are not perfect We make errors in design and code
  • 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. 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. 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. 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. 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. 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. 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. 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. 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. Basics Spock lets you write specifications that describe expected features (properties, aspects) exhibited by a system of interest
  • 15. import spock.lang.* Package spock.lang contains the most important types for writing specifications
  • 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. … contd  Specification contains a number of useful methods for writing specifications  Instructs JUnit to run specification withSputnik, Spock's JUnit runner
  • 18. Fields  Declarations: def obj = new Class() @Shared res = new VeryExpensiveResource()
  • 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. Blocks  A test case can have following blocks:  setup  when //for stimulus  then //output comparison  expect  where
  • 21. Example
  • 22. Expect Block  It is useful in situations where it is more natural to describe stimulus and expected response in a single expression
  • 23. Where block • It is used to write data-driven feature methods
  • 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. Data Tables • A convenient way to exercise a feature method with a fixed set of data
  • 26. Data Pipes • A data pipe, indicated by the left-shift (<<) operator, connects a data variable to a data provider
  • 27. @Unroll • A method annotated with @Unroll will have its iterations reported independently
  • 28. Exception Conditions • They are used to describe that a when block should throw an exception
  • 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. ..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. 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. 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. 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. 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. 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. 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. Verification Of Interactions
  • 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. 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. ...contd.  Accessing Method Arguments  subscriber.receive(_) >> { String message -> message.size() > 3 ? "ok" : "fail" }  Throw an exception:  subscriber.receive(_) >> { throw new InternalError("ouch") }
  • 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. References      unit-testing/
  • 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 :