31
Unit Testing Using SPOCK

Unit test-using-spock in Grails

Embed Size (px)

Citation preview

Page 1: Unit test-using-spock in Grails

Unit Testing

Using SPOCK

Page 2: Unit test-using-spock in Grails

AgendaTestingUnit TestingSpock Unit TestingUnit Test CasesDemoPractice

Page 3: Unit test-using-spock in Grails

TestinGTesting is to check the equality of “What program supposed to do” and “what actually program does”.

Program supposed to do == Program actually does

Page 4: Unit test-using-spock in Grails

why we need testingWe 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.

Page 5: Unit test-using-spock in Grails

What testing doesIt is process of executing software with the intention of finding errors.

It can help us to find undiscovered errors.

Page 6: Unit test-using-spock in Grails

Type of testingUnit Testing

Integration Testing

Functional Testing

Page 7: Unit test-using-spock in Grails

Unit testingIndividual 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.

Page 8: Unit test-using-spock in Grails

Pros and cons of Unit testingPros:- 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.

Page 9: Unit test-using-spock in Grails

SpockA developer testing framework for Java and Groovy application.Based on Groovy.Spock lets us to write specifications that describe expected features.

Page 10: Unit test-using-spock in Grails

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

Page 11: Unit test-using-spock in Grails

SpecificationsA 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

Page 12: Unit test-using-spock in Grails

Fixture MethodsFixture methods are responsible for setting up and cleaning up the environment in which feature methods are rundef setup() //run before every feature methoddef cleanup() //run after every feature methoddef setupSpec() //run before the first feature methoddef cleanupSpec() //run after the last feature method

Feature Method:- def “pushing a new element in the stack”(){}

Page 13: Unit test-using-spock in Grails

BlocksA test can have following blocks:-setupwhen //for the stimulusthen //output comparisonexpectwhere

Page 14: Unit test-using-spock in Grails

Examplewhen:stack.push(elem)then:!stack.emptystack.size()>0stack.peek()=elem

Page 15: Unit test-using-spock in Grails

Expect blockIt is more natural to describe stimulus and expected response in a single expression:-when:def x=Math.max(1,2)then:x==2expect:Math.max(1,2)==2

Page 16: Unit test-using-spock in Grails

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 } }

Page 17: Unit test-using-spock in Grails

Data-TableA 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 } }

Page 18: Unit test-using-spock in Grails

Data-pipeA data-pipe, indicated by left shift(<<)

where: a<<[3, 7, 0] b<<[5, 0, 0] c<<[5, 7, 0]

Page 19: Unit test-using-spock in Grails

@UnrollA method annoted with @unroll will have its iterations reported independently

@Unroll def “max of two num”(){ … }

@Unroll “#a and #b and result is #c”

Page 20: Unit test-using-spock in Grails

Exception Conditionsetup: Stack stack=new Stack()

when: stack.pop()

then: thrown(EmptyStackException) stack.empty

Page 21: Unit test-using-spock in Grails

mockingA 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()

Page 22: Unit test-using-spock in Grails

Mocking MethodsmockDomain()Mock()mockConfig()mockLogging()

Page 23: Unit test-using-spock in Grails

mockDomainAdds 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()

Page 24: Unit test-using-spock in Grails

MockIt can be used to mock any of the class.Return an Object of the class.MyService service = Mock()service.anyMethod(a, b)>>result

Page 25: Unit test-using-spock in Grails

Test mixinsSince grails 2.0, a collection of unit testing mixins is provided.e.g., @TestFor(COntroller_Name) @IgnoreRest@Mock([domain1, domain2]) @FailsWith@Timeout@Ignore

Page 26: Unit test-using-spock in Grails

TestforIt 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.

Page 27: Unit test-using-spock in Grails

StubbingStubbing 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!”)}

Page 28: Unit test-using-spock in Grails

Questions

Page 29: Unit test-using-spock in Grails

References

Page 30: Unit test-using-spock in Grails

Basic Commandsgrails [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

Page 31: Unit test-using-spock in Grails

Thank You

Presented By:- Vijay Shukla