Unit test-using-spock in Grails

Post on 06-Apr-2017

517 views 0 download

Transcript of Unit test-using-spock in Grails

Unit Testing

Using SPOCK

AgendaTestingUnit TestingSpock Unit TestingUnit Test CasesDemoPractice

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

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

It can help us to find undiscovered errors.

Type of testingUnit Testing

Integration Testing

Functional Testing

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.

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.

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

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

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”(){}

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

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

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

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

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

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

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

Exception Conditionsetup: Stack stack=new Stack()

when: stack.pop()

then: thrown(EmptyStackException) stack.empty

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

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

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

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

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

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.

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

Questions

References

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

Thank You

Presented By:- Vijay Shukla