Grails unit testing

  • 3,383 views
Uploaded on

testing slideshare api

testing slideshare api

More in: Technology , Education
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
No Downloads

Views

Total Views
3,383
On Slideshare
0
From Embeds
0
Number of Embeds
2

Actions

Shares
Downloads
38
Comments
0
Likes
1

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide
  • .
  • .
  • .
  • .
  • .
  • .

Transcript

  • 1. Grails Unit Testing By:- Uday & Imran
  • 2. Agenda
    • Testing overview
    • 3. Understanding Unit Testing
    • 4. Goals of Unit Testing
    • 5. Spock Unit Testing
    • 6. Writing Unit test cases
    • 7. Demo
    • 8. Exercise
  • 9. What do we test ?
      What a program is supposed to do == What the program actually does
  • 10. 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.
  • 11. A way of thinking
    • Designing and coding are creative
    • 12. Testing is destructive.The primary goal is to break the software
    • 13. Very often the same person does coding and testing
    • 14. 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.
    • 15. We have more code base to handle
  • 16. Testing
    • Testing is a process of executing software with the intent of finding errors.
    • 17. Good Testing has high probability of finding as-yet-undiscovered errors
    • 18. Successful Testing discovers errors
      • If it did not find any errors, need to ask whether our testing approach is good or not
  • 19. Testing needs to be the integral part at each level of development
    • Unit testing (white box)
    • 20. Integration testing (white box)
    • 21. Functional testing (black box)
    • 22. Acceptance testing
  • 23.
      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.
    • 24. A unit is the smallest testable part of an application.
    • 25. Each test case is independent from the others: substitutes like method stubs, mock objects, can be used to assist testing a module in isolation.
    • 26. A unit test provides a strict, written contract that the piece of code must satisfy.
    • 27. It tests individual methods or blocks of code without considering for surrounding infrastructure.
    • 28. It is integral part of the development, so developers write unit test cases.
  • 29. Shortcomings of Unit Testing
    • Test cases ‐written to suit programmer’s implementation (not necessarily specification)
    • 30. The actual database or external file is never tested directly by TDD.
    • 31. It is highly reliant on Refactoring and Programmer skills
    • 32. Not every code is testable.
  • 33.
      Advantages of Unit Testing
    • Facilitates change
    • 34. Unit testing allows the programmer to refactor code at a later date, and make sure the module still works correctly
    • 35. Simplifies integration
    • 36. 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.
    • 37. Documentation
    • 38. Unit testing provides a sort of living documentation of the system
    • 39. Design
    • 40. 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.
    • 41. Quality
    Improves the quality, readability and testability of the code
  • 42. Spock
    • A developer testing framework for Java and Groovy application
    • 43. Based on Groovy
    • 44. What makes it stand out from the crowd is its beautiful and highly expressive specification language
  • 45. Getting started Basic Terms used in Spock
  • 46. Fields
    • Field: store objects belonging to the specification's fixture
      • def obj = new ClassUnderSpecification()
      • 47. @Shared res =newVeryExpensiveResource()
      • 48. static final PI = 3.141592654
  • 49. Fixture Methods
    • def setup() {} // run before every feature method
    • 50. def cleanup() {} // run after every feature method
    • 51. def setupSpec() {} // run before the first feature method
    • 52. def cleanupSpec() {} // run after the last feature method
  • 53. Feature methods def "pushing an element on the stack"() { // blocks go here }
  • 54. Blocks
    • setup: (optional)
    • 55. when, then, (always occure togethor)
      • when:(stimulus)
      • 56. then: (response)
    • expect: useful in situations where it is more natural to describe stimulus and expected response in a single expression
  • 57. Example when: stack.push(elem) then: !stack.empty stack.size() == 1 stack.peek() == elem
  • 58. Example when: def x = Math.max(1, 2) then: x == 2 expect: Math.max(1, 2) == 2
  • 59. Where (for data driven testing)
    • data-driven feature methods
    • 60. where block always comes last in a method
    expect: Math.max(a, b) == c where: [a,b,c] << [[1,2,2],[3,7,7]]
  • 61. Exception conditions when: emptyStack.pop() then: thrown(EmptyStackException) emptyStack.empty
  • 62. def &quot;testing exception is not thrown&quot;() { when: //something that does'nt throw an exception then: notThrown(NullPointerException) }
  • 63. More annotations @Timeout @Ignore @IgnoreRest @FailsWith
  • 64. Unit testing in grails context
    • simple an quick to run
    • 65. small focused tests
    • 66. doesn't load supporting components
    • 67. doesn't spin up the whole Grails environment
    • 68. dynamic methods and properties are not available
    • 69. found under test/unit
  • 70.
      ...contd
    • All unit test case files extend UnitSpec
    • 71. All controller unit test case file extend ControllerSpec
    • 72. All taglib tests files extend TaglibSpec
    • 73. All integration test files extend IntegrationSpec
    • 74. All integration test files for gsp extend GroovyPagesSpec
    • 75. Specification is the super class of all
  • 76.
      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; }
  • 77. Mocking Methods
    • mockDomain()
    • 78. Mock() (SPOCK SPECIAL)
    • 79. mockConfig()
    • 80. mockForConstraintsTests()
    • 81. mockLogging()
  • 82. mockDomain()
    • adds the persistence methods back onto the domain class
    • 83. Injected methods mockDomain() gives us
    • 84. All of your dynamic finders (findBy* and findAllBy* )
    • 85. get(), getAll(), exists(), count(), list(), create(), save(), validate(), delete(), discard(), addTo(), removeFrom()
    • 86. Injected methods that aren’t included:
    • 87. countBy(), createCriteria(), executeQuery(), executeUpdate(), find(), findAll(), findAllWhere(), findWhere(), ident(), listOrderBy(), merge(), withCriteria(), withTransaction()
  • 88. Contd...
      def instances = [] mockDomain(MyDomain, instances) MyDomain object = new MyDomain(name: 'name') object.save()
  • 89. Mock()
    • It can be used to mock any class you want
    • 90. Returns an object of the class
    • 91. MyService myService = Mock()
    • 92. myService.someMethod(argument1,argument) >> result
    • 93. myService.someMethod(_) >> result
  • 94.
      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
  • 95. MockConfig()
      This is used for mocking Config properties
    • void savePerson(String name) {
    • 96. Person person = new Person()
    • 97. person.name = name
    • 98. person.bankAccount =config.bank.accountNumber
    • 99. person.save()
    • 100. }
  • 101. Contd...
      def “test my function”() { Setup:
    mockDomain(Person)
      mockConfig('''
    bank{ accountNumber = '1234567' } ''') when:
      def personService = new PersonService() personService.savePerson(“Name”)
    then:
      Person.count()==1 }
  • 102. 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; }
  • 103. MockLogging()
      Used to access the log property void getEmployeeAddresses() { def anyText = &quot;hello world&quot; log.debug anyText }
    • Test
    • 104. def “test my method which uses logging”() {
    • 105. mockLogging(EmployeeService, true)
    • 106. //
    • 107. }
  • 108. Function with dependencies
      public void myFunction(String empId) { String name = otherService.someOtherFunction(empId) MyDomainClass object = new MyDomainClass(name: name) object.save() }
    • Test Case
    • 109. 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 }
  • 110. ControllerSpec readymade goodies
  • 117. 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) }
  • 118. 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 }
  • 119. Spock in grails context
      renderArgs.model.book==book // For testing model parameters renderArgs.view=='show' // For testing view renderArgs.template=='show' // For testing template
  • 120. 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()
  • 121.
      Questions???
  • 122. References
    • http://mrhaki.blogspot.com/2009/04/unit-testing-constraints-in-domain.html
    • 123. http://www.grails.org/Unit+Testing
    • 124. http://meetspock.appspot.com/?id=9001
    • 125. http://code.google.com/p/spock/wiki/SpockBasics
    • 126. http://code.google.com/p/spock/wiki/Interactions
    • 127. http://www.grails.org/doc/1.1/guide/9.%20Testing.html
    • 128. http://www.make-go-now.com/2009/04/17/ode-to-mockformarch-part-2-mockdomain/
    • 129. http://www.make-go-now.com/2009/03/05/ode-to-mockformarch-part-1-testing-constraints/
  • 130.
      Thanks (Testing is like walking everybody knows its good but nobody does it)