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

Weitere ähnliche Inhalte

Was ist angesagt?

Unit testing on embedded target with C++Test
Unit testing on embedded  target with C++TestUnit testing on embedded  target with C++Test
Unit testing on embedded target with C++TestEngineering Software Lab
 
Oh so you test? - A guide to testing on Android from Unit to Mutation
Oh so you test? - A guide to testing on Android from Unit to MutationOh so you test? - A guide to testing on Android from Unit to Mutation
Oh so you test? - A guide to testing on Android from Unit to MutationPaul Blundell
 
Qtp-training A presentation for beginers
Qtp-training  A presentation for beginersQtp-training  A presentation for beginers
Qtp-training A presentation for beginersDhavamani Prakash
 
ScalaUA - distage: Staged Dependency Injection
ScalaUA - distage: Staged Dependency InjectionScalaUA - distage: Staged Dependency Injection
ScalaUA - distage: Staged Dependency Injection7mind
 
Mastering Mock Objects - Advanced Unit Testing for Java
Mastering Mock Objects - Advanced Unit Testing for JavaMastering Mock Objects - Advanced Unit Testing for Java
Mastering Mock Objects - Advanced Unit Testing for JavaDenilson Nastacio
 
Sample Chapter of Practical Unit Testing with TestNG and Mockito
Sample Chapter of Practical Unit Testing with TestNG and MockitoSample Chapter of Practical Unit Testing with TestNG and Mockito
Sample Chapter of Practical Unit Testing with TestNG and MockitoTomek Kaczanowski
 
QTP Interview Questions and answers
QTP Interview Questions and answersQTP Interview Questions and answers
QTP Interview Questions and answersRita Singh
 
Automated Regression Testing for Embedded Systems in Action
Automated Regression Testing for Embedded Systems in ActionAutomated Regression Testing for Embedded Systems in Action
Automated Regression Testing for Embedded Systems in ActionAANDTech
 
Qtp 9.5 Tutorials by www.onsoftwaretest.com
Qtp 9.5 Tutorials by www.onsoftwaretest.comQtp 9.5 Tutorials by www.onsoftwaretest.com
Qtp 9.5 Tutorials by www.onsoftwaretest.comonsoftwaretest
 
Applying TDD to Legacy Code
Applying TDD to Legacy CodeApplying TDD to Legacy Code
Applying TDD to Legacy CodeAlexander Goida
 
Testing in-python-and-pytest-framework
Testing in-python-and-pytest-frameworkTesting in-python-and-pytest-framework
Testing in-python-and-pytest-frameworkArulalan T
 
Unit Testing - The Whys, Whens and Hows
Unit Testing - The Whys, Whens and HowsUnit Testing - The Whys, Whens and Hows
Unit Testing - The Whys, Whens and Howsatesgoral
 
Unit testing best practices
Unit testing best practicesUnit testing best practices
Unit testing best practicesnickokiss
 
Google mock training
Google mock trainingGoogle mock training
Google mock trainingThierry Gayet
 
RPG Program for Unit Testing RPG
RPG Program for Unit Testing RPG RPG Program for Unit Testing RPG
RPG Program for Unit Testing RPG Greg.Helton
 

Was ist angesagt? (20)

Unit testing on embedded target with C++Test
Unit testing on embedded  target with C++TestUnit testing on embedded  target with C++Test
Unit testing on embedded target with C++Test
 
Oh so you test? - A guide to testing on Android from Unit to Mutation
Oh so you test? - A guide to testing on Android from Unit to MutationOh so you test? - A guide to testing on Android from Unit to Mutation
Oh so you test? - A guide to testing on Android from Unit to Mutation
 
Cpp unit
Cpp unit Cpp unit
Cpp unit
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
Unit testing with java
Unit testing with javaUnit testing with java
Unit testing with java
 
Qtp-training A presentation for beginers
Qtp-training  A presentation for beginersQtp-training  A presentation for beginers
Qtp-training A presentation for beginers
 
ScalaUA - distage: Staged Dependency Injection
ScalaUA - distage: Staged Dependency InjectionScalaUA - distage: Staged Dependency Injection
ScalaUA - distage: Staged Dependency Injection
 
Mastering Mock Objects - Advanced Unit Testing for Java
Mastering Mock Objects - Advanced Unit Testing for JavaMastering Mock Objects - Advanced Unit Testing for Java
Mastering Mock Objects - Advanced Unit Testing for Java
 
JMockit
JMockitJMockit
JMockit
 
Sample Chapter of Practical Unit Testing with TestNG and Mockito
Sample Chapter of Practical Unit Testing with TestNG and MockitoSample Chapter of Practical Unit Testing with TestNG and Mockito
Sample Chapter of Practical Unit Testing with TestNG and Mockito
 
QTP Interview Questions and answers
QTP Interview Questions and answersQTP Interview Questions and answers
QTP Interview Questions and answers
 
Automated Regression Testing for Embedded Systems in Action
Automated Regression Testing for Embedded Systems in ActionAutomated Regression Testing for Embedded Systems in Action
Automated Regression Testing for Embedded Systems in Action
 
Qtp 9.5 Tutorials by www.onsoftwaretest.com
Qtp 9.5 Tutorials by www.onsoftwaretest.comQtp 9.5 Tutorials by www.onsoftwaretest.com
Qtp 9.5 Tutorials by www.onsoftwaretest.com
 
AAA Automated Testing
AAA Automated TestingAAA Automated Testing
AAA Automated Testing
 
Applying TDD to Legacy Code
Applying TDD to Legacy CodeApplying TDD to Legacy Code
Applying TDD to Legacy Code
 
Testing in-python-and-pytest-framework
Testing in-python-and-pytest-frameworkTesting in-python-and-pytest-framework
Testing in-python-and-pytest-framework
 
Unit Testing - The Whys, Whens and Hows
Unit Testing - The Whys, Whens and HowsUnit Testing - The Whys, Whens and Hows
Unit Testing - The Whys, Whens and Hows
 
Unit testing best practices
Unit testing best practicesUnit testing best practices
Unit testing best practices
 
Google mock training
Google mock trainingGoogle mock training
Google mock training
 
RPG Program for Unit Testing RPG
RPG Program for Unit Testing RPG RPG Program for Unit Testing RPG
RPG Program for Unit Testing RPG
 

Ähnlich wie Grails 1.1 Testing - Unit, Integration & Functional

Monitoring using Prometheus and Grafana
Monitoring using Prometheus and GrafanaMonitoring using Prometheus and Grafana
Monitoring using Prometheus and GrafanaArvind Kumar G.S
 
[xp2013] Narrow Down What to Test
[xp2013] Narrow Down What to Test[xp2013] Narrow Down What to Test
[xp2013] Narrow Down What to TestZsolt Fabok
 
Mockito with a hint of PowerMock
Mockito with a hint of PowerMockMockito with a hint of PowerMock
Mockito with a hint of PowerMockYing Zhang
 
A la découverte des google/mock (aka gmock)
A la découverte des google/mock (aka gmock)A la découverte des google/mock (aka gmock)
A la découverte des google/mock (aka gmock)Thierry Gayet
 
Performance testing and j meter
Performance testing and j meterPerformance testing and j meter
Performance testing and j meterPurna Chandar
 
Test driven development in .Net - 2010 + Eclipse
Test driven development in .Net - 2010 + EclipseTest driven development in .Net - 2010 + Eclipse
Test driven development in .Net - 2010 + EclipseUTC Fire & Security
 
Joomla! Testing - J!DD Germany 2016
Joomla! Testing - J!DD Germany 2016Joomla! Testing - J!DD Germany 2016
Joomla! Testing - J!DD Germany 2016Yves Hoppe
 
Pragmatic Java Test Automation
Pragmatic Java Test AutomationPragmatic Java Test Automation
Pragmatic Java Test AutomationDmitry Buzdin
 
Grails unit testing
Grails unit testingGrails unit testing
Grails unit testingpleeps
 
Selenium-Browser-Based-Automated-Testing-for-Grails-Apps
Selenium-Browser-Based-Automated-Testing-for-Grails-AppsSelenium-Browser-Based-Automated-Testing-for-Grails-Apps
Selenium-Browser-Based-Automated-Testing-for-Grails-Appschrisb206 chrisb206
 
Testing your application on Google App Engine
Testing your application on Google App EngineTesting your application on Google App Engine
Testing your application on Google App EngineInphina Technologies
 
Testing Your Application On Google App Engine
Testing Your Application On Google App EngineTesting Your Application On Google App Engine
Testing Your Application On Google App EngineIndicThreads
 
Integration tests: use the containers, Luke!
Integration tests: use the containers, Luke!Integration tests: use the containers, Luke!
Integration tests: use the containers, Luke!Roberto Franchini
 
Appium TestNG Framework and Multi-Device Automation Execution
Appium TestNG Framework and Multi-Device Automation ExecutionAppium TestNG Framework and Multi-Device Automation Execution
Appium TestNG Framework and Multi-Device Automation ExecutionpCloudy
 
Building Maintainable Android Apps (DroidCon NYC 2014)
Building Maintainable Android Apps (DroidCon NYC 2014)Building Maintainable Android Apps (DroidCon NYC 2014)
Building Maintainable Android Apps (DroidCon NYC 2014)Kevin Schultz
 
Test strategy for web development
Test strategy for web developmentTest strategy for web development
Test strategy for web developmentalice yang
 

Ähnlich wie Grails 1.1 Testing - Unit, Integration & Functional (20)

Monitoring using Prometheus and Grafana
Monitoring using Prometheus and GrafanaMonitoring using Prometheus and Grafana
Monitoring using Prometheus and Grafana
 
Unit testing - A&BP CC
Unit testing - A&BP CCUnit testing - A&BP CC
Unit testing - A&BP CC
 
[xp2013] Narrow Down What to Test
[xp2013] Narrow Down What to Test[xp2013] Narrow Down What to Test
[xp2013] Narrow Down What to Test
 
Mockito with a hint of PowerMock
Mockito with a hint of PowerMockMockito with a hint of PowerMock
Mockito with a hint of PowerMock
 
Lesson 2
Lesson 2Lesson 2
Lesson 2
 
A la découverte des google/mock (aka gmock)
A la découverte des google/mock (aka gmock)A la découverte des google/mock (aka gmock)
A la découverte des google/mock (aka gmock)
 
Beyond Unit Testing
Beyond Unit TestingBeyond Unit Testing
Beyond Unit Testing
 
Performance testing and j meter
Performance testing and j meterPerformance testing and j meter
Performance testing and j meter
 
Test driven development in .Net - 2010 + Eclipse
Test driven development in .Net - 2010 + EclipseTest driven development in .Net - 2010 + Eclipse
Test driven development in .Net - 2010 + Eclipse
 
Joomla! Testing - J!DD Germany 2016
Joomla! Testing - J!DD Germany 2016Joomla! Testing - J!DD Germany 2016
Joomla! Testing - J!DD Germany 2016
 
Pragmatic Java Test Automation
Pragmatic Java Test AutomationPragmatic Java Test Automation
Pragmatic Java Test Automation
 
Grails unit testing
Grails unit testingGrails unit testing
Grails unit testing
 
Selenium-Browser-Based-Automated-Testing-for-Grails-Apps
Selenium-Browser-Based-Automated-Testing-for-Grails-AppsSelenium-Browser-Based-Automated-Testing-for-Grails-Apps
Selenium-Browser-Based-Automated-Testing-for-Grails-Apps
 
Testing your application on Google App Engine
Testing your application on Google App EngineTesting your application on Google App Engine
Testing your application on Google App Engine
 
Testing Your Application On Google App Engine
Testing Your Application On Google App EngineTesting Your Application On Google App Engine
Testing Your Application On Google App Engine
 
Integration tests: use the containers, Luke!
Integration tests: use the containers, Luke!Integration tests: use the containers, Luke!
Integration tests: use the containers, Luke!
 
Appium TestNG Framework and Multi-Device Automation Execution
Appium TestNG Framework and Multi-Device Automation ExecutionAppium TestNG Framework and Multi-Device Automation Execution
Appium TestNG Framework and Multi-Device Automation Execution
 
Building Maintainable Android Apps (DroidCon NYC 2014)
Building Maintainable Android Apps (DroidCon NYC 2014)Building Maintainable Android Apps (DroidCon NYC 2014)
Building Maintainable Android Apps (DroidCon NYC 2014)
 
Test strategy for web development
Test strategy for web developmentTest strategy for web development
Test strategy for web development
 
JavaScript Unit Testing
JavaScript Unit TestingJavaScript Unit Testing
JavaScript Unit Testing
 

Kürzlich hochgeladen

AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 

Kürzlich hochgeladen (20)

AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 

Grails 1.1 Testing - Unit, Integration & Functional

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