Grails Unit Testing By:-  Uday & Imran
Agenda <ul><li>Testing overview
Understanding Unit Testing
Goals of Unit Testing
Spock Unit Testing
Writing Unit test cases
Demo
Exercise </li></ul>
What do we test ? <ul>What a program is supposed to do  ==  What the program actually does </ul>
Motivation <ul><li>People are not perfect </li><ul><li>We make errors in design and code </li></ul><li>Testing is an inves...
A way of thinking <ul><li>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...
We have more code base to handle </li></ul>
Testing <ul><li>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 </li><ul><li>If it did not find any errors, need to ask whether our testing approach ...
Testing needs to be the integral part at each level of development <ul><li>Unit testing (white box)
Integration testing (white box)
Functional testing (black box)
Acceptance testing  </li></ul>
<ul>Understanding Unit Testing </ul><ul><li>Unit testing is a method by which individual units of source code are tested t...
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 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. </li></ul>
Shortcomings of Unit Testing <ul><li>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. </li></ul>
<ul>Advantages of Unit Testing </ul><ul><li>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 testi...
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...
Quality </li></ul>Improves the quality, readability and testability of the code
Spock <ul><li>A developer testing framework for Java and Groovy application
Based on Groovy
Upcoming SlideShare
Loading in...5
×

Grails unit testing

3,762

Published on

testing slideshare api

Published in: Technology, Education
0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
3,762
On Slideshare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
50
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide
  • .
  • .
  • .
  • .
  • .
  • .
  • Grails unit testing

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

      Clipping is a handy way to collect important slides you want to go back to later.

    ×