Grails Spock Testing

44

Transcript of Grails Spock Testing

Page 1: Grails Spock Testing
Page 2: Grails Spock Testing

GRAILS SPOCK

TESTING

Page 3: Grails Spock Testing

Agenda

1. Testingoverview

2. Understanding UnitTesting

3. Spock UnitTesting

4. Writing Unit test cases

5. Demo

6. Exercise

Page 4: Grails Spock Testing

What do we test ?

What a program issupposed to do

==

What the program actuallydoes

Page 5: Grails Spock Testing

Motivation

Peopleare not perfect

We make errors in design and code

Page 6: Grails Spock Testing

Testing is an Investment

Over the time the testsbuild, the

early investment in writingtest

cases pays dividends later as the

sizeof the application grows

Page 7: Grails Spock Testing

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

Page 8: Grails Spock Testing

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

• If it did not, need to ask whether our testing approach isgood or not

Page 9: Grails Spock Testing

Integral Part of Development

• Testingneedstobe integralpartateach levelof development

• Types:

• Unit testing (whitebox)

• Integration testing (whitebox)

• Functional testing (blackbox)

• Acceptance testing

Page 10: Grails Spock Testing

Understanding Unit testing

• Individual unitsof 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 areused

• Tests individual methods or blocks without considering the

surrounding infrastructure

• A unit test provides a strict contract that a piece of code MUSTsatisfy

Page 11: Grails Spock Testing

Disadvantages of Unit testing

• Test cases ‐written to suit programmer’s implementation(not

necessarily specification)

• The actual database or external file isnever tested directly

• Highly reliant on Refactoring and Programming skils

Page 12: Grails Spock Testing

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 livingdocumentation of a system

Page 13: Grails Spock Testing

Advantages of Unit testing

• Evolvesdesign

• In“TestDriven 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

Page 14: Grails Spock Testing

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

Page 15: Grails Spock Testing

Basics

Spockletsyouwritespecificationsthatdescribeexpected features

(properties,aspects)exhibitedby a systemof interest

Page 16: Grails Spock Testing

import spock.lang.*

Package spock.lang containsthemostimportanttypesforwriting

specifications

Page 17: Grails Spock Testing

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.

Page 18: Grails Spock Testing

… contd

• Specification contains a number of useful methods for writing

specifications

• Instructs JUnit to run specification withSputnik, Spock's JUnitrunner

Page 19: Grails Spock Testing

Fields

• Declarations:

• def obj =newClass()

• @Shared res =newVeryExpensiveResource()

Page 20: Grails Spock Testing

Fixture Methods

• Fixturemethods are responsible for setting up and cleaning up the

environment in which feature methods are run.

• def setup(){}

• def cleanup(){}

• def setupSpec(){}

• def cleanupSpec() {}

Page 21: Grails Spock Testing

Blocks

• A test case can have following blocks:

• setup

• when //forstimulus

• then //output comparison

• expect

• where

Page 22: Grails Spock Testing

Example

Page 23: Grails Spock Testing

Expect Block

• Itisuseful in situations where itis

more natural to describestimulus

and expected response in a

singleexpression

Page 24: Grails Spock Testing

Where block

• Itisused to write data-driven featuremethods

Page 25: Grails Spock Testing

Data Driven Testing

• Itisuseful to exercise the same test code multiple times,with varying

inputs and expected results.

• Itisa firstclass feature in Spock

Page 26: Grails Spock Testing

Data Tables

• A convenient way to exercise a

feature method with a fixed set

of data

Page 27: Grails Spock Testing

Data Pipes

• A data pipe, indicated by the

left-shift (<<)operator, connects a

data variable to a data provider.

Page 28: Grails Spock Testing

@Unroll

• A method annotated with @Unrol will have its iterations reported

independently

Page 29: Grails Spock Testing

Exception Conditions

• They are used to describe that a when block should throw an

exception

Page 30: Grails Spock Testing

Mocking

• Mock objects literally implement (orextend) the type they stand in

for

• Initiallymock 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 isonly equal to itself, has a unique hash code, and a

string representation that includes the name of the type it represents

Page 31: Grails Spock Testing

..contd.

• Thisdefault behavior isoverrideable by stubbing the methods

• Mock objects are created with the MockingApi.Mock()

• def subscriber =Mock(Subscriber)

• Subscriber subsriber =Mock()

Page 32: Grails Spock Testing

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 this list.

Page 33: Grails Spock Testing

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])

Page 34: Grails Spock Testing

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])

Page 35: Grails Spock Testing

TestFor Annotation

• The TestForannotation defines a class under test and will

automatically create a field for the type of class under test

• For example, @TestFor(BookController) thiswill automaticallycreate

“controller” field

• IfTestForwas defined for a service then a “service” field would be

created

Page 36: Grails Spock Testing

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

Page 37: Grails Spock Testing

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”)

Page 38: Grails Spock Testing

Verification Of Interactions

Page 39: Grails Spock Testing

Stubbing

• Stubbing is the act of making collaborators respond to method calls

in acertain way

• Inother words stubbing is justproviding dummy implementation of a

method

Page 40: Grails Spock Testing

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"]

Page 41: Grails Spock Testing

...contd.

• Accessing Method Arguments

• subscriber.receive(_) >>{String message ->message.size()

>3 ? "ok":"fail"}

• Throw anexception:

• subscriber.receive(_) >>{throw new InternalError("ouch")}

Page 42: Grails Spock Testing

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.

Page 43: Grails Spock Testing

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/

Page 44: Grails Spock 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!