Grails unit testing
Upcoming SlideShare
Loading in...5
×
 

Grails unit testing

on

  • 3,735 views

testing slideshare api

testing slideshare api

Statistics

Views

Total Views
3,735
Slideshare-icon Views on SlideShare
3,723
Embed Views
12

Actions

Likes
0
Downloads
35
Comments
0

1 Embed 12

https://dev.uniience.com 12

Accessibility

Categories

Upload Details

Uploaded via as OpenOffice

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • .
  • .
  • .
  • .
  • .
  • .

Grails unit testing Grails unit testing Presentation Transcript

  • Grails Unit Testing By:- Uday & Imran
  • Agenda
    • Testing overview
    • Understanding Unit Testing
    • Goals of 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 the size of the application grows.
  • A way of thinking
    • Designing and coding are creative
    • Testing is destructive.The primary goal is to break the software
    • Very often the same person does coding and testing
    • Need 'split personality': when you start testing, become paranoid and malicious. Surprisingly hard to do: people don't like finding out that they make mistakes.
    • We have more code base to handle
  • Testing
    • Testing is a process of executing software with the intent of finding errors.
    • Good Testing has high probability of finding as-yet-undiscovered errors
    • Successful Testing discovers errors
      • If it did not find any errors, need to ask whether our testing approach is good or not
  • Testing needs to be the integral part at each level of development
    • Unit testing (white box)
    • Integration testing (white box)
    • Functional testing (black box)
    • Acceptance testing
    • Understanding Unit Testing
    • Unit testing is a method by which individual units of source code are tested to determine if they are fit for use.
    • A unit is the smallest testable part of an application.
    • Each test case is independent from the others: substitutes like method stubs, mock objects, can be used to assist testing a module in isolation.
    • A unit test provides a strict, written contract that the piece of code must satisfy.
    • It tests individual methods or blocks of code without considering for surrounding infrastructure.
    • It is integral part of the development, so developers write unit test cases.
  • Shortcomings of Unit Testing
    • Test cases ‐written to suit programmer’s implementation (not necessarily specification)
    • The actual database or external file is never tested directly by TDD.
    • It is highly reliant on Refactoring and Programmer skills
    • Not every code is testable.
    • Advantages of Unit Testing
    • Facilitates change
    • Unit testing allows the programmer to refactor code at a later date, and make sure the module still works correctly
    • Simplifies integration
    • Unit testing may reduce uncertainty in the units themselves and can be used in a bottom-up testing style approach.By testing the parts of a program first and then testing the sum of its parts, integration testing becomes much easier.
    • Documentation
    • Unit testing provides a sort of living documentation of the system
    • Design
    • When software is developed using a test-driven approach, the unit test may take the place of formal design. Each unit test can be seen as a design element specifying classes, methods, and observable behaviour.
    • Quality
    Improves the quality, readability and testability of the code
  • 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
  • Getting started Basic Terms used in Spock
  • Fields
    • Field: store objects belonging to the specification's fixture
      • def obj = new ClassUnderSpecification()
      • @Shared res =newVeryExpensiveResource()
      • static final PI = 3.141592654
  • Fixture Methods
    • def setup() {} // run before every feature method
    • def cleanup() {} // run after every feature method
    • def setupSpec() {} // run before the first feature method
    • def cleanupSpec() {} // run after the last feature method
  • Feature methods def "pushing an element on the stack"() { // blocks go here }
  • Blocks
    • setup: (optional)
    • when, then, (always occure togethor)
      • when:(stimulus)
      • then: (response)
    • expect: useful in situations where it is more natural to describe stimulus and expected response in a single expression
  • Example when: stack.push(elem) then: !stack.empty stack.size() == 1 stack.peek() == elem
  • Example when: def x = Math.max(1, 2) then: x == 2 expect: Math.max(1, 2) == 2
  • Where (for data driven testing)
    • data-driven feature methods
    • where block always comes last in a method
    expect: Math.max(a, b) == c where: [a,b,c] << [[1,2,2],[3,7,7]]
  • Exception conditions when: emptyStack.pop() then: thrown(EmptyStackException) emptyStack.empty
  • def &quot;testing exception is not thrown&quot;() { when: //something that does'nt throw an exception then: notThrown(NullPointerException) }
  • More annotations @Timeout @Ignore @IgnoreRest @FailsWith
  • Unit testing in grails context
    • simple an quick to run
    • small focused tests
    • doesn't load supporting components
    • doesn't spin up the whole Grails environment
    • dynamic methods and properties are not available
    • found under test/unit
    • ...contd
    • All unit test case files extend UnitSpec
    • All controller unit test case file extend ControllerSpec
    • All taglib tests files extend TaglibSpec
    • All integration test files extend IntegrationSpec
    • All integration test files for gsp extend GroovyPagesSpec
    • Specification is the super class of all
    • class MyService { public String myFunction() { return &quot;testString&quot; } } Test Case def “test my simple function”() {
    setup:
      def myService = new MyService()
    when:
      String string = myService.myFunction()
    then:
      string==&quot;testString&quot; }
  • Mocking Methods
    • mockDomain()
    • Mock() (SPOCK SPECIAL)
    • mockConfig()
    • mockForConstraintsTests()
    • mockLogging()
  • mockDomain()
    • adds the persistence methods back onto the domain class
    • Injected methods mockDomain() gives us
    • All of your dynamic finders (findBy* and findAllBy* )
    • get(), getAll(), exists(), count(), list(), create(), save(), validate(), delete(), discard(), addTo(), removeFrom()
    • Injected methods that aren’t included:
    • countBy(), createCriteria(), executeQuery(), executeUpdate(), find(), findAll(), findAllWhere(), findWhere(), ident(), listOrderBy(), merge(), withCriteria(), withTransaction()
  • Contd...
      def instances = [] mockDomain(MyDomain, instances) MyDomain object = new MyDomain(name: 'name') object.save()
  • Mock()
    • It can be used to mock any class you want
    • Returns an object of the class
    • MyService myService = Mock()
    • myService.someMethod(argument1,argument) >> result
    • myService.someMethod(_) >> result
    • public void myFunction(int number, String name){ MyDomainClass object = new MyDomainClass(age: number, name: name) object.save() } Test Case def “test if my domain object is saved” () { def instances = [] mockDomain(MyDomainClass) def myService = new MyService() myService.myFunction(30, 'myName') MyDomain.count()==1 }
    Test saving an object
  • MockConfig()
      This is used for mocking Config properties
    • void savePerson(String name) {
    • Person person = new Person()
    • person.name = name
    • person.bankAccount =config.bank.accountNumber
    • person.save()
    • }
  • Contd...
      def “test my function”() { Setup:
    mockDomain(Person)
      mockConfig('''
    bank{ accountNumber = '1234567' } ''') when:
      def personService = new PersonService() personService.savePerson(“Name”)
    then:
      Person.count()==1 }
  • Contd...
      def “only user with valid name passes the constraint”() { setup: mockForConstraintsTests(User) when: def user = new User(name:&quot;&quot;, login:&quot;admin&quot;, password:&quot;pass&quot;) user.validate() then: user.errors.errorCount==1 user.errors[&quot;name&quot;]==&quot;blank&quot; }
  • MockLogging()
      Used to access the log property void getEmployeeAddresses() { def anyText = &quot;hello world&quot; log.debug anyText }
    • Test
    • def “test my method which uses logging”() {
    • mockLogging(EmployeeService, true)
    • //
    • }
  • Function with dependencies
      public void myFunction(String empId) { String name = otherService.someOtherFunction(empId) MyDomainClass object = new MyDomainClass(name: name) object.save() }
    • Test Case
    • def “test my function with dependency on other service”() {
    setup:
      OtherService otherService = Mock(OtherService) otherService.someOtherFunction(1001) >> &quot;testName&quot; def myService = new MyService() myService.otherService = otherService
    when:
      String string = myService.myFunction( 'myName')
    then:
      instances.size()==1 }
  • ControllerSpec readymade goodies
    • mockRequest
    • mockResponse
    • mockSession
    • forwardArgs
    • redirectArgs
    • renderArgs
    • mockParams
  • Code
      def commit = { BankFile bankFile = BankFile.get(params.id) try { bankFileService.commit(bankFile, params.comments) flash.message = &quot;Bank File has been committed&quot; } catch (BankFileCommitException e) { flash.message = &quot;Bank File commit failed: ${e.message}&quot; redirect(action: show, id: bankFile.id) }
  • Test Def “test my simple action ”() { Setup: mockDomain(BankFile, [new BankFile(id: 1)]) BankFileService serviceMock = Mock() serviceMock.commit(params) >> new BankFile(id: 1) } controller.bankFileService = serviceMock when: mockParams.id = 1 controller.commit() then: redirectArgs.action==”show” redirectArgs.id==1 }
  • Spock in grails context
      renderArgs.model.book==book // For testing model parameters renderArgs.view=='show' // For testing view renderArgs.template=='show' // For testing template
  • Spock in grails context
      Mocking Response mockResponse.contentAsString=='success' mockResponse.contentAsByteArray == bytes mockResponse.contentType = &quot;image/gif&quot; Mocking Request Cookie cookie = new Cookie(&quot;A&quot;, &quot;ABCD&quot;) mockRequest.cookies = [cookie].toArray()
    • Questions???
  • References
    • http://mrhaki.blogspot.com/2009/04/unit-testing-constraints-in-domain.html
    • http://www.grails.org/Unit+Testing
    • http://meetspock.appspot.com/?id=9001
    • http://code.google.com/p/spock/wiki/SpockBasics
    • http://code.google.com/p/spock/wiki/Interactions
    • http://www.grails.org/doc/1.1/guide/9.%20Testing.html
    • http://www.make-go-now.com/2009/04/17/ode-to-mockformarch-part-2-mockdomain/
    • http://www.make-go-now.com/2009/03/05/ode-to-mockformarch-part-1-testing-constraints/
    • Thanks (Testing is like walking everybody knows its good but nobody does it)