Grails 1.1 Testing<br />Tech Talk @ 2Paths<br />July 17, 2009<br />By Dave Koo<br />©2009 - 2Paths Solutions Ltd. (www.2pa...
Agenda<br />Unit Testing<br />Integration Testing<br />Functional Testing<br />Putting It All Together<br />©2009 - 2Paths...
Unit Testing - Overview<br />unit tests enable testing small bits of code in isolation<br />Grails does NOT inject any sur...
Unit Testing - Benefits<br />find problems sooner -&gt; you can test your code before all it&apos;s dependencies are creat...
Unit Testing - Drawbacks<br />more code to maintain & debug -&gt; often as buggy as code under test (if written by same pe...
Unit Testing – GrailsUnitTestCaseOverview<br />extends GroovyTestCase to add Grails-specific mocking and make testing more...
Unit Testing – GrailsUnitTestCasemethods<br />mockFor(class, loose = false)<br />mockDomain(class, testInstances[ ])<br />...
Unit Testing – GrailsUnitTestCasemockFor(class, loose = false)<br />generic mocker for mocking methods of any class<br />r...
Unit Testing – GrailsUnitTestCasemockDomain(class, testInstances[ ])<br />mocks all methods (instance, static & dynamic) o...
Unit Testing – GrailsUnitTestCaseother methods…<br />mockForConstraintsTests(class, testInstances[ ])<br />Stripped-down v...
Unit Testing – ControllerUnitTestCase<br />extends GrailsUnitTestCase to add mocks for:<br />all dynamic properties & meth...
Unit Testing – Other Unit Tests<br />TagLibUnitTestCase<br />extends GrailsUnitTestCase to add mocks for dynamic propertie...
Integration Testing - Overview<br />used to test that an entire module or sub-system consisting of multiple classes is wor...
Integration Testing - Benefits<br />tests the real interactions between individual pieces<br />finds more complex bugs tha...
Integration Testing - Drawbacks<br />perhaps overused by lazy testers who don&apos;t feel like mocking :)<br />requires mo...
Functional Testing - Overview<br />used to test functionality from an end user&apos;s perspective across all layers of the...
Functional Testing - Benefits<br />finds complex system-level and inter-module bugs<br />finds UI bugs<br />can be written...
Functional Testing - Drawbacks<br />very slow to execute HTTP level tests<br />often more cumbersome to write than other t...
Functional Testing - Tools<br />CanooWebTest& Grails Functional Testing<br />Both wrap HtmlUnit which provides a Java API ...
Functional Testing - WebTest<br />test organization & re-use<br />grouping steps with ant.group<br />calling methods from ...
Functional Testing – WebTestgrouping steps with ant.group<br />if your test has dozens of steps, it gets hard to read the ...
Functional Testing – WebTestcalling methods from other tests<br />Instead of copying & pasting the same methods from one t...
Functional Testing – WebTestGroovy step<br />If you need to execute arbitrary Groovy code in your test, use WebTest’sgroov...
Functional Testing – WebTestGroovy step<br />test method with Groovy step to test AJAX autocomplete form input:<br />def s...
Putting It All Together - Running tests<br />test-app -&gt; all tests<br />test-app -unit -&gt; all unit tests<br />test-a...
Putting It All Together - Summary<br />Unit testing -  taglibs, controllers, services, domain classes (including contraint...
Upcoming SlideShare
Loading in...5
×

Grails 1.1 Testing - Unit, Integration & Functional

5,099

Published on

A walkthrough of the benefits, drawbacks, new features, important "gotchas" and some code samples using the testing features available in Grails 1.1.

We'll be covering:

- unit testing (specifically GrailsUnitTestCase and it's extensions)
- integration testing
- functional testing (using WebTest)

Published in: Technology
1 Comment
9 Likes
Statistics
Notes
No Downloads
Views
Total Views
5,099
On Slideshare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
166
Comments
1
Likes
9
Embeds 0
No embeds

No notes for slide

Grails 1.1 Testing - Unit, Integration & Functional

  1. 1. Grails 1.1 Testing<br />Tech Talk @ 2Paths<br />July 17, 2009<br />By Dave Koo<br />©2009 - 2Paths Solutions Ltd. (www.2paths.com)<br />7/17/09<br />
  2. 2. Agenda<br />Unit Testing<br />Integration Testing<br />Functional Testing<br />Putting It All Together<br />©2009 - 2Paths Solutions Ltd. (www.2paths.com)<br />7/17/09<br />
  3. 3. Unit Testing - Overview<br />unit tests enable testing small bits of code in isolation<br />Grails does NOT inject any surrounding infrastructure (ie. no dynamic GORM methods, database, Spring resources, bootstrap, ServletContext, etc)<br />©2009 - 2Paths Solutions Ltd. (www.2paths.com)<br />7/17/09<br />
  4. 4. Unit Testing - Benefits<br />find problems sooner -&gt; you can test your code before all it&apos;s dependencies are created/available<br />enables safer refactoring (of individual classes)<br />faster to run than integration & functional tests<br />there isn&apos;t a big speed gap early in the project (PLAID: unit ~ 10s, integration ~ 30)<br />but it grows as the system gets bigger<br />makes TDD less painful -&gt; breaks problem into smaller pieces<br />provides form of API documentation & spec<br />©2009 - 2Paths Solutions Ltd. (www.2paths.com)<br />7/17/09<br />
  5. 5. Unit Testing - Drawbacks<br />more code to maintain & debug -&gt; often as buggy as code under test (if written by same person :)<br />sometimes you have to mock a LOT of stuff before you can write your little test<br />doesn&apos;t catch bugs at the integration or UI layers -&gt; can create false sense of security<br />©2009 - 2Paths Solutions Ltd. (www.2paths.com)<br />7/17/09<br />
  6. 6. Unit Testing – GrailsUnitTestCaseOverview<br />extends GroovyTestCase to add Grails-specific mocking and make testing more convenient for Grails users<br />mocking is test-specific and doesn&apos;t leak from one test to another<br />avoids having to do a lot of MetaClass hacking (and forgetting to teardown your metaclass hacking :)<br />©2009 - 2Paths Solutions Ltd. (www.2paths.com)<br />7/17/09<br />
  7. 7. Unit Testing – GrailsUnitTestCasemethods<br />mockFor(class, loose = false)<br />mockDomain(class, testInstances[ ])<br />mockForConstraintsTests(class, testInstances[ ])<br />mockLogging(class, enableDebug = false)<br />Code samples: http://grails.org/doc/1.1.1/guide/9.%20Testing.html#9.1%20Unit%20Testing<br />©2009 - 2Paths Solutions Ltd. (www.2paths.com)<br />7/17/09<br />
  8. 8. Unit Testing – GrailsUnitTestCasemockFor(class, loose = false)<br />generic mocker for mocking methods of any class<br />returns a control object (not the actual mock)<br />loose - false == strict mocking (sequence of expected method calls matters), true == loose (sequence doesn&apos;t matter)<br />methods - you can mock instance or static methods<br />demands - your expectations of the mock<br />range - number of times a method is expected to be called (default === 1)<br />closure - mock implementation of the method<br />strictControl.createMock() - returns an actual mock object<br />strictControl.verify() - verifies that all demands were actually met<br />©2009 - 2Paths Solutions Ltd. (www.2paths.com)<br />7/17/09<br />
  9. 9. Unit Testing – GrailsUnitTestCasemockDomain(class, testInstances[ ])<br />mocks all methods (instance, static & dynamic) on a domain class<br />testInstances- a list of domain class instances which replaces and acts as the &quot;database”<br />you can call save(), findBy*(), validate(), etc on an instance of a mocked domain class<br />inheritance can be tricky!<br />assume you have ParentClass, ChildA, ChildB<br />if you mock ParentClass and pass a collection of instances containing ChildA and/or ChildB objects to the MockDomain() method, you must ensure that you have already mocked each type of ChildX class in the instance collection. This is needed even if you NEVER call a dynamic method on any child class (such as ChildClass.list()).<br />always mock a child class BEFORE mocking its parent, otherwise you may get &quot;Method Not Found&quot; exceptions when calling dynamic methods on the child<br />new addition to Grails<br />still some bugs / missing features<br />check Grails&apos; JIRA & mailing lists if experiencing wierdbehaviour<br />©2009 - 2Paths Solutions Ltd. (www.2paths.com)<br />7/17/09<br />
  10. 10. Unit Testing – GrailsUnitTestCaseother methods…<br />mockForConstraintsTests(class, testInstances[ ])<br />Stripped-down version of mockDomain that allows for assertions to validate domain class constraints<br />Takes the pain out of testing domain class constraints<br />mockLogging(class, enableDebug = false)<br />Adds a mock &quot;log&quot; property to a class. Any messages passed to the mock logger are echoed to the console.<br />©2009 - 2Paths Solutions Ltd. (www.2paths.com)<br />7/17/09<br />
  11. 11. Unit Testing – ControllerUnitTestCase<br />extends GrailsUnitTestCase to add mocks for:<br />all dynamic properties & methods Grails injects into controllers (render, redirect, model, etc)<br />all HTTP objects available to controllers (request, response, session, params, flash, etc)<br />command object (if needed)<br />provides an implicit &quot;controller&quot; property which contains all the above mocks (no need to def the controller yourself in your test class)<br />don&apos;t forget to mock your Domain objects as needed if the controller action you call expects a database<br />©2009 - 2Paths Solutions Ltd. (www.2paths.com)<br />7/17/09<br />
  12. 12. Unit Testing – Other Unit Tests<br />TagLibUnitTestCase<br />extends GrailsUnitTestCase to add mocks for dynamic properties & methods a TagLibexpects<br />dbUnit<br />extends jUnit to allow you to test that your DB is in the expected state<br />prevents subsequent tests from failing due to a previous test leaving the database &quot;dirty&quot;<br />©2009 - 2Paths Solutions Ltd. (www.2paths.com)<br />7/17/09<br />
  13. 13. Integration Testing - Overview<br />used to test that an entire module or sub-system consisting of multiple classes is working correctly (in isolation)<br />one level below a functional test as integration tests do not test the entire stack<br />Grails injects all the surrounding infrastructure such as data sources & Spring beans<br />pretty straightforward to implement since there&apos;s generally no mocking involved<br />where to use integration tests??? we&apos;ll come back to this in a few mins :)<br />©2009 - 2Paths Solutions Ltd. (www.2paths.com)<br />7/17/09<br />
  14. 14. Integration Testing - Benefits<br />tests the real interactions between individual pieces<br />finds more complex bugs that unit tests can&apos;t find<br />faster to run than functional tests (usually)<br />makes large-scale refactoring safer<br />find bugs sooner -&gt; doesn&apos;t require other system modules to be built<br />©2009 - 2Paths Solutions Ltd. (www.2paths.com)<br />7/17/09<br />
  15. 15. Integration Testing - Drawbacks<br />perhaps overused by lazy testers who don&apos;t feel like mocking :)<br />requires more code to be written than unit tests<br />doesn&apos;t find system-level or inter-module bugs<br />value is debatable if you have good functional tests & good unit tests.<br />©2009 - 2Paths Solutions Ltd. (www.2paths.com)<br />7/17/09<br />
  16. 16. Functional Testing - Overview<br />used to test functionality from an end user&apos;s perspective across all layers of the system<br />©2009 - 2Paths Solutions Ltd. (www.2paths.com)<br />7/17/09<br />
  17. 17. Functional Testing - Benefits<br />finds complex system-level and inter-module bugs<br />finds UI bugs<br />can be written by non-techies (depends on tool used)<br />provides &quot;done when&quot; acceptance criteria for the customer<br />provides a form of user documentation<br />makes large-scale refactoring safer<br />©2009 - 2Paths Solutions Ltd. (www.2paths.com)<br />7/17/09<br />
  18. 18. Functional Testing - Drawbacks<br />very slow to execute HTTP level tests<br />often more cumbersome to write than other types of tests<br />often brittle and can require a lot of maintenance (especially if tied to UI)<br />Usually hard to write until UI is available (and stable)<br />©2009 - 2Paths Solutions Ltd. (www.2paths.com)<br />7/17/09<br />
  19. 19. Functional Testing - Tools<br />CanooWebTest& Grails Functional Testing<br />Both wrap HtmlUnit which provides a Java API that mocks a web browser<br />CanooWebTest<br />wrapper for WebTest&apos;s XML syntax<br />and therefore constrained by the underlying XML syntax<br />Grails Functional Testing<br />pure-groovy solution<br />more flexible, but newer & therefore fewer features than WebTest<br />©2009 - 2Paths Solutions Ltd. (www.2paths.com)<br />7/17/09<br />
  20. 20. Functional Testing - WebTest<br />test organization & re-use<br />grouping steps with ant.group<br />calling methods from other tests<br />Groovy step<br />notation uses 3 double-quotes as Groovy code delimeter (“””)<br />accessing HtmlUnit for fine-grained test control<br />parameter passing between app context & WebTest context<br />AJAX testing w/ sleep()<br />©2009 - 2Paths Solutions Ltd. (www.2paths.com)<br />7/17/09<br />
  21. 21. Functional Testing – WebTestgrouping steps with ant.group<br />if your test has dozens of steps, it gets hard to read the report<br />grouping steps with ant.group rolls them up to 1 line in the test report, which can be easily expanded/collapsed:<br />ant.group(description: “verify bank account info”) { invoke “someController/someAction”verifyText “some text”verifyText “more text”}<br />©2009 - 2Paths Solutions Ltd. (www.2paths.com)<br />7/17/09<br />
  22. 22. Functional Testing – WebTestcalling methods from other tests<br />Instead of copying & pasting the same methods from one test to another, you can call a method in another test by passing it your AntBuilder instance (ant) as a param. This ensures the test steps are executed using the calling test’s AntBuilder.<br />====== in CallingTestClass() ====def otherTestClass = new OtherTestClass()otherTestClass.someMethod(ant)====== in OtherTestClass() =====def someMethod(AntBuilderab) {ab.invoke“someController/someAction”ab.verifyText“some text”}<br />©2009 - 2Paths Solutions Ltd. (www.2paths.com)<br />7/17/09<br />
  23. 23. Functional Testing – WebTestGroovy step<br />If you need to execute arbitrary Groovy code in your test, use WebTest’sgroovy step.<br />Keep in mind that this groovy step won’t have access to any Groovy variables defined in your test (such as method params)…it only has access to the properties in the AntBuilder context.<br />So you need to pass any needed params to the AntBuilder before entering your groovy step. Then you can retrieve them from the AntBuilder from within your step.<br />The following example involves:<br />Storing Groovy variables into AntBuilder properties<br />Retrieving AntBuilder properties for use in the Groovy step<br />Calling some HtmlUnit methods which aren’t available in WebTest for fine-grained test control<br />Pausing the test for 2 seconds (very useful with AJAX tests to give the server time to respond<br />©2009 - 2Paths Solutions Ltd. (www.2paths.com)<br />7/17/09<br />
  24. 24. Functional Testing – WebTestGroovy step<br />test method with Groovy step to test AJAX autocomplete form input:<br />def setAJAXInputField(elementId, elementValue, AntBuilderab) {ab.storeProperty(property: &apos;elementId&apos;, value: elementId)<br />ab.storeProperty(property: &apos;elementValue&apos;, value: elementValue)<br />ab.groovy &quot;&quot;” def elementId = step.webtestProperties.elementId<br /> def elementValue = step.webtestProperties.elementValue def document = step.context.currentResponse.documentElement<br />def element = document.getHtmlElementById(elementId)<br />element.focus()<br />element.type(elementValue)<br /> Thread.sleep(2000)“””<br />}<br />©2009 - 2Paths Solutions Ltd. (www.2paths.com)<br />7/17/09<br />
  25. 25. Putting It All Together - Running tests<br />test-app -&gt; all tests<br />test-app -unit -&gt; all unit tests<br />test-app -integration -&gt; all integration tests<br />test-app -unit AnnualReportAssignmentHandler-&gt; 2 unit tests & all integration tests<br />test-app AnnualReportAssignmentHandlerWorkflowManagerService-&gt; 2 unit tests & 1 integration test<br />run-webtest-&gt; runs all tests using new server instance<br />run-webtest -nostart-&gt; runs all tests using existing Tomcat instance (much faster!!!)<br />run-webtestClassNameTestName-&gt; run TestName using existing Tomcat instance<br />©2009 - 2Paths Solutions Ltd. (www.2paths.com)<br />7/17/09<br />
  26. 26. Putting It All Together - Summary<br />Unit testing - taglibs, controllers, services, domain classes (including contraints), other delegates & &quot;helpers&quot;, even your data (dbUnit)<br />Integration testing<br />now that Grails 1.1 supports unit testing of controllers with ControllerUnitTestCase, that seems to be the preferred way of testing them (rather than using integration tests).<br />This makes sense since controllers should not be doing the heavy lifting in a Grails app.<br />The same holds true for TagLib testing with TagLibUnitTestCase.<br />this leaves Services as the most valuable thing to cover with integration tests (but only after you’ve written unit tests for them )<br />Functional testing - smoke tests, acceptance tests, regression tests<br />Manual testing by humans - look & feel, anything not covered above<br />©2009 - 2Paths Solutions Ltd. (www.2paths.com)<br />7/17/09<br />
  1. A particular slide catching your eye?

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

×