SlideShare a Scribd company logo
1 of 51
Download to read offline
Testing Web Applications with Spring 3.2

Sam Brannen, Swiftmind, @sam_brannen
Rossen Stoyanchev, VMware, @rstoya05




                                       © 2012 SpringSource, by VMware. All rights reserved
Today's Speakers




                   2
Sam Brannen
   Spring and Java Consultant @ Swiftmind
   Developing Java for over 15 years
   Spring Framework Core Committer since 2007
   Spring Trainer
   Presenter on Spring, Java, OSGi, and testing




                                                   3
Rossen Stoyanchev
 Spring Framework core committer
 Focus on Spring Web
 Main developer of Spring MVC Test




                                      4
Agenda
 Spring TestContext Framework Updates
 Spring MVC Test Framework
 Q&A




                                         5
Spring TestContext Framework Updates




                                       6
What's New in the Spring TCF?
   Upgraded to JUnit 4.11 and TestNG 6.5.2
   Loading WebApplicationContexts
   Testing request- and session-scoped beans
   Support for ApplicationContextInitializers
   Loading context hierarchies (3.2.1)
   And more… (see presentation from SpringOne 2GX 2012)




                                                           7
Loading a WebApplicationContext
 Q: How do you tell the TestContext Framework to load a
 WebApplicationContext?


 A: Just annotate your test class with @WebAppConfiguration!




                                                               8
@WebAppConfiguration
 Denotes that the context should be a WebApplicationContext

 Configures the resource path for the web app
 • Used by MockServletContext
 • Defaults to “src/main/webapp”
 • Paths are file-system folders, relative to the project root not classpath resources
 • The classpath: prefix is also supported




                                                                                         9
Example: @WebAppConfiguration




                                10
Example: @WebAppConfiguration




                                11
Example: @WebAppConfiguration




                                12
ServletTestExecutionListener
 Sets up default thread-local state via RequestContextHolder before
 each test method
 Creates:
 • MockHttpServletRequest
 • MockHttpServletResponse
 • ServletWebRequest
 Ensures that the MockHttpServletResponse and ServletWebRequest
 can be injected into the test instance
 Cleans up thread-local state after each test method


                                                                       13
Example: Injecting Mocks




                           14
Web Scopes – Review



 request: lifecycle tied to the current HttpServletRequest



 session: lifecycle tied to the current HttpSession




                                                              15
Example: Request-scoped Bean Test




                                    16
Example: Request-scoped Bean Config




                                      17
Example: Session-scoped Bean Test




                                    18
Example: Session-scoped Bean Config




                                      19
ApplicationContextInitializer
 Introduced in Spring 3.1
 Used for programmatic initialization of a
 ConfigurableApplicationContext
 For example:
 • to register property sources
 • to activate profiles against the Environment
 Configured in web.xml by specifying contextInitializerClasses via
 • context-param for the ContextLoaderListener
 • init-param for the DispatcherServlet


                                                                      20
Example: Multiple Initializers




                                 21
Using Initializers in Tests
 Configured in @ContextConfiguration via the initializers attribute
 Inheritance can be controlled via the inheritInitializers attribute
 An ApplicationContextInitializer may configure the entire context
 • XML resource locations or annotated classes are no longer required
 Initializers are now part of the context cache key
 Initializers are ordered based on Spring's Ordered interface or the
 @Order annotation




                                                                        22
Application Context Hierarchies
 Currently only flat, non-hierarchical contexts are supported in tests.

 There’s no easy way to create contexts with parent-child
 relationships.


 But… hierarchies are supported in production.

 Wouldn’t it be nice if you could test them, too?!



                                                                       23
Testing Context Hierarchies in version 3.2.2 (!)
 New @ContextHierarchy annotation
 • used in conjunction with @ContextConfiguration


 @ContextConfiguration now supports a ‘name’ attribute
 • for merging and overriding hierarchy configuration




                                                          24
Single Test with Context Hierarchy




                                     25
Class and Context Hierarchies




                                26
Built-in Spring MVC Test Support




                                   27
Overview
   Dedicated support for testing Spring MVC applications
   Fluent API
   Very easy to write
   Includes client and server-side support
   Servlet container not required




                                                            28
In More Detail
 Included in spring-test module of Spring Framework 3.2
 Builds on
 • TestContext framework for loading Spring MVC configuration
 • MockHttpServletRequest/Response and other “mock” types
 Server-side tests involve DispatcherServlet
 Client-side REST testing for code using RestTemplate




                                                                29
Spring MVC Test History
 Evolved as independent project on Github
 • https://github.com/SpringSource/spring-test-mvc

 Now folded into Spring Framework 3.2

 Former project still supports Spring Framework 3.1




                                                       30
Server-Side Example




                      31
A Note On Fluent API Usage
 Requires static imports

   import static MockMvcRequestBuilders.get;
   import static MockMvcResultMatchers.status;

   mockMvc.perform(get(“/foo”)).andExpect(status().isOk())


 Add as “favorite static members” in Eclipse preferences
 • Java -> Editor -> Content Assist -> Favorites




                                                             32
Server-Side Test Recap
   Actual Spring MVC configuration loaded
   MockHttpServletRequest prepared
   Executed via DispatcherServlet
   Assertions applied on the resulting MockHttpServletResponse




                                                                  33
Integration Or Unit Testing?
 Mock request/response types, no Servlet container
 However..
 • DispatcherServlet + actual Spring MVC configuration used

 Hence..
 • Not full end-to-end testing, i.e. does not replace Selenium
 • However provides full confidence in Spring MVC web layer

 In short, integration testing for Spring MVC
 • Don't get too caught up in terminology!

                                                                 34
Strategy For Testing
 Focus on testing the Spring MVC web layer alone
 • Inject controllers with mock services or database repositories
 Thoroughly test Spring MVC
 • Including code and configuration
 Separate from lower layer integration tests
 • E.g. database tests




                                                                    35
Declaring A Mock Dependency
 Since we're loading actual Spring MVC config
 Need to declare mock dependencies
   <bean class="org.mockito.Mockito" factory-method="mock">
     <constructor-arg value="org.example.FooDao"/>
   </bean>
 Then simply inject the mock instance into the test class
 • Via @Autowired
 • Set up and reset via @Before, @Test, and @After methods




                                                              36
What Can Be Tested?
 Response status, headers, and content
 • Focus on asserting these first...
 Spring MVC and Servlet specific results
 • Model, flash, session, request attributes
 • Mapped controller method and interceptors
 • Resolved exceptions
 Various options for asserting the response body
 • JSONPath, XPath, XMLUnit
 • Hamcrest matchers


                                                    37
What About the View Layer?
 All view templating technologies will work
 • Freemarker/Velocity, Thymeleaf, JSON, XML, PDF, etc.
 Except for JSPs (no Servlet container!)
 • You can however assert the selected JSP
 No redirecting and forwarding
 • You can however assert the redirected or forwarded URL
 Also of interest
 • HTML Unit / Selenium Driver integration (experimental)
 • https://github.com/SpringSource/spring-test-mvc-htmlunit


                                                              38
Useful Option For Debugging
 Print all details to the console, i.e. System.out

   mockMvc.perform("/foo")
        .andDo(print())
        .andExpect(status().Ok())




                                                      39
“Standalone” Setup
 No Spring configuration is loaded
 Test one controller at a time
 Just provide the controller instance




                                         40
“Standalone” Setup Example




                             41
Tests with Servlet Filters




                             42
Re-use Request Properties and Expectations




                                             43
Direct Access to the Underlying MvcResult




                                            44
Client-Side REST Example




                           45
Client-Side REST Test Recap
 An instance of RestTemplate configured with custom
 ClientHttpRequestFactory
 Records and asserts expected requests
 • Instead of executing them
 Code using RestTemlpate can now be invoked
 Use verify() to assert all expectations were executed




                                                          46
Acknowledgements


The Spring MVC Test support draws
inspiration from similar test framework in
Spring Web Services




                                             47
Further Resources: Spring MVC Test
 Reference doc chapter on Spring MVC Test
 Sample tests in the framework source code
 • https://github.com/SpringSource/spring-framework/tree/3.2.x/spring-test-
   mvc/src/test/java/org/springframework/test/web/servlet/samples
 • https://github.com/SpringSource/spring-framework/tree/3.2.x/spring-test-
   mvc/src/test/java/org/springframework/test/web/client/samples
 Tests in spring-mvc-showcase
 • https://github.com/SpringSource/spring-mvc-showcase




                                                                              48
Further Resources Cont'd
 Spring Framework
 • http://www.springsource.org/spring-framework
 • Reference manual and Javadoc
 Forums
 • http://forum.springframework.org
 JIRA
 • http://jira.springframework.org
 GitHub
 • https://github.com/SpringSource/spring-framework




                                                      49
Blogs
 SpringSource Team Blog
 • http://blog.springsource.com/


 Swiftmind Team Blog
 • http://www.swiftmind.com/blog/




                                    50
Q&A
 Sam Brannen
 • twitter: @sam_brannen
 • www.slideshare.net/sbrannen
 • www.swiftmind.com


 Rossen Stoyanchev
 • twitter: @rstoya05




                                 51

More Related Content

What's hot

Spring Framework 4.1
Spring Framework 4.1Spring Framework 4.1
Spring Framework 4.1Sam Brannen
 
Testing Web Apps with Spring Framework 3.2
Testing Web Apps with Spring Framework 3.2Testing Web Apps with Spring Framework 3.2
Testing Web Apps with Spring Framework 3.2Sam Brannen
 
Spring 3.1 to 3.2 in a Nutshell - Spring I/O 2012
Spring 3.1 to 3.2 in a Nutshell - Spring I/O 2012Spring 3.1 to 3.2 in a Nutshell - Spring I/O 2012
Spring 3.1 to 3.2 in a Nutshell - Spring I/O 2012Sam Brannen
 
Introduction to Apache Maven
Introduction to Apache MavenIntroduction to Apache Maven
Introduction to Apache MavenRajind Ruparathna
 
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 with JUnit 5 and Spring
Testing with JUnit 5 and SpringTesting with JUnit 5 and Spring
Testing with JUnit 5 and SpringVMware Tanzu
 
Maven Presentation - SureFire vs FailSafe
Maven Presentation - SureFire vs FailSafeMaven Presentation - SureFire vs FailSafe
Maven Presentation - SureFire vs FailSafeHolasz Kati
 
An Introduction to Maven Part 1
An Introduction to Maven Part 1An Introduction to Maven Part 1
An Introduction to Maven Part 1MD Sayem Ahmed
 
Spring 4 final xtr_presentation
Spring 4 final xtr_presentationSpring 4 final xtr_presentation
Spring 4 final xtr_presentationsourabh aggarwal
 
JUnit 5 — New Opportunities for Testing on the JVM
JUnit 5 — New Opportunities for Testing on the JVMJUnit 5 — New Opportunities for Testing on the JVM
JUnit 5 — New Opportunities for Testing on the JVMVMware Tanzu
 
Learning Maven by Example
Learning Maven by ExampleLearning Maven by Example
Learning Maven by ExampleHsi-Kai Wang
 

What's hot (20)

Spring Framework 4.1
Spring Framework 4.1Spring Framework 4.1
Spring Framework 4.1
 
Testing Web Apps with Spring Framework 3.2
Testing Web Apps with Spring Framework 3.2Testing Web Apps with Spring Framework 3.2
Testing Web Apps with Spring Framework 3.2
 
Spring 3.1 to 3.2 in a Nutshell - Spring I/O 2012
Spring 3.1 to 3.2 in a Nutshell - Spring I/O 2012Spring 3.1 to 3.2 in a Nutshell - Spring I/O 2012
Spring 3.1 to 3.2 in a Nutshell - Spring I/O 2012
 
Introduction to Apache Maven
Introduction to Apache MavenIntroduction to Apache Maven
Introduction to Apache Maven
 
Spring Test Framework
Spring Test FrameworkSpring Test Framework
Spring Test Framework
 
Apache DeltaSpike the CDI toolbox
Apache DeltaSpike the CDI toolboxApache DeltaSpike the CDI toolbox
Apache DeltaSpike the CDI toolbox
 
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 with JUnit 5 and Spring
Testing with JUnit 5 and SpringTesting with JUnit 5 and Spring
Testing with JUnit 5 and Spring
 
Maven Presentation - SureFire vs FailSafe
Maven Presentation - SureFire vs FailSafeMaven Presentation - SureFire vs FailSafe
Maven Presentation - SureFire vs FailSafe
 
Maven basics
Maven basicsMaven basics
Maven basics
 
Maven
MavenMaven
Maven
 
Maven ppt
Maven pptMaven ppt
Maven ppt
 
Apache Maven
Apache MavenApache Maven
Apache Maven
 
An Introduction to Maven Part 1
An Introduction to Maven Part 1An Introduction to Maven Part 1
An Introduction to Maven Part 1
 
Spring 4 final xtr_presentation
Spring 4 final xtr_presentationSpring 4 final xtr_presentation
Spring 4 final xtr_presentation
 
JUnit 5 — New Opportunities for Testing on the JVM
JUnit 5 — New Opportunities for Testing on the JVMJUnit 5 — New Opportunities for Testing on the JVM
JUnit 5 — New Opportunities for Testing on the JVM
 
JDBC
JDBCJDBC
JDBC
 
Learning Maven by Example
Learning Maven by ExampleLearning Maven by Example
Learning Maven by Example
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Demystifying Maven
Demystifying MavenDemystifying Maven
Demystifying Maven
 

Similar to Testing Web Apps with Spring Framework 3.2

Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework Serhat Can
 
Spring 3.1 in a Nutshell
Spring 3.1 in a NutshellSpring 3.1 in a Nutshell
Spring 3.1 in a NutshellSam Brannen
 
Refactoring Legacy Web Forms for Test Automation
Refactoring Legacy Web Forms for Test AutomationRefactoring Legacy Web Forms for Test Automation
Refactoring Legacy Web Forms for Test AutomationStephen Fuqua
 
Spring 3.1 and MVC Testing Support
Spring 3.1 and MVC Testing SupportSpring 3.1 and MVC Testing Support
Spring 3.1 and MVC Testing SupportSam Brannen
 
Spring Testing, Fight for the Context
Spring Testing, Fight for the ContextSpring Testing, Fight for the Context
Spring Testing, Fight for the ContextGlobalLogic Ukraine
 
Unit 38 - Spring MVC Introduction.pptx
Unit 38 - Spring MVC Introduction.pptxUnit 38 - Spring MVC Introduction.pptx
Unit 38 - Spring MVC Introduction.pptxAbhijayKulshrestha1
 
Spring 3.1 in a Nutshell - JAX London 2011
Spring 3.1 in a Nutshell - JAX London 2011Spring 3.1 in a Nutshell - JAX London 2011
Spring 3.1 in a Nutshell - JAX London 2011Sam Brannen
 
Spring Day | Spring 3.1 in a Nutshell | Sam Brannen
Spring Day | Spring 3.1 in a Nutshell | Sam BrannenSpring Day | Spring 3.1 in a Nutshell | Sam Brannen
Spring Day | Spring 3.1 in a Nutshell | Sam BrannenJAX London
 
Spring MVC framework features and concepts
Spring MVC framework features and conceptsSpring MVC framework features and concepts
Spring MVC framework features and conceptsAsmaShaikh478737
 
Spring 3.1: a Walking Tour
Spring 3.1: a Walking TourSpring 3.1: a Walking Tour
Spring 3.1: a Walking TourJoshua Long
 
Multi Client Development with Spring
Multi Client Development with SpringMulti Client Development with Spring
Multi Client Development with SpringJoshua Long
 
Kirill Rozin - Practical Wars for Automatization
Kirill Rozin - Practical Wars for AutomatizationKirill Rozin - Practical Wars for Automatization
Kirill Rozin - Practical Wars for AutomatizationSergey Arkhipov
 
Java J2EE Interview Questions Part 2
Java J2EE Interview Questions Part 2Java J2EE Interview Questions Part 2
Java J2EE Interview Questions Part 2javatrainingonline
 
Spring framework in depth
Spring framework in depthSpring framework in depth
Spring framework in depthVinay Kumar
 
Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Tuna Tore
 
springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892Tuna Tore
 
Testing Microservices
Testing MicroservicesTesting Microservices
Testing MicroservicesAnil Allewar
 

Similar to Testing Web Apps with Spring Framework 3.2 (20)

Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
Spring 3.1 in a Nutshell
Spring 3.1 in a NutshellSpring 3.1 in a Nutshell
Spring 3.1 in a Nutshell
 
Refactoring Legacy Web Forms for Test Automation
Refactoring Legacy Web Forms for Test AutomationRefactoring Legacy Web Forms for Test Automation
Refactoring Legacy Web Forms for Test Automation
 
Spring 3.1 and MVC Testing Support
Spring 3.1 and MVC Testing SupportSpring 3.1 and MVC Testing Support
Spring 3.1 and MVC Testing Support
 
Spring Testing, Fight for the Context
Spring Testing, Fight for the ContextSpring Testing, Fight for the Context
Spring Testing, Fight for the Context
 
Unit 38 - Spring MVC Introduction.pptx
Unit 38 - Spring MVC Introduction.pptxUnit 38 - Spring MVC Introduction.pptx
Unit 38 - Spring MVC Introduction.pptx
 
Spring 3.1 in a Nutshell - JAX London 2011
Spring 3.1 in a Nutshell - JAX London 2011Spring 3.1 in a Nutshell - JAX London 2011
Spring 3.1 in a Nutshell - JAX London 2011
 
Spring Day | Spring 3.1 in a Nutshell | Sam Brannen
Spring Day | Spring 3.1 in a Nutshell | Sam BrannenSpring Day | Spring 3.1 in a Nutshell | Sam Brannen
Spring Day | Spring 3.1 in a Nutshell | Sam Brannen
 
Spring MVC framework features and concepts
Spring MVC framework features and conceptsSpring MVC framework features and concepts
Spring MVC framework features and concepts
 
Next stop: Spring 4
Next stop: Spring 4Next stop: Spring 4
Next stop: Spring 4
 
Spring 3.1: a Walking Tour
Spring 3.1: a Walking TourSpring 3.1: a Walking Tour
Spring 3.1: a Walking Tour
 
Multi Client Development with Spring
Multi Client Development with SpringMulti Client Development with Spring
Multi Client Development with Spring
 
Kirill Rozin - Practical Wars for Automatization
Kirill Rozin - Practical Wars for AutomatizationKirill Rozin - Practical Wars for Automatization
Kirill Rozin - Practical Wars for Automatization
 
Spring MVC Framework
Spring MVC FrameworkSpring MVC Framework
Spring MVC Framework
 
Java J2EE Interview Questions Part 2
Java J2EE Interview Questions Part 2Java J2EE Interview Questions Part 2
Java J2EE Interview Questions Part 2
 
Java J2EE Interview Question Part 2
Java J2EE Interview Question Part 2Java J2EE Interview Question Part 2
Java J2EE Interview Question Part 2
 
Spring framework in depth
Spring framework in depthSpring framework in depth
Spring framework in depth
 
Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5
 
springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892
 
Testing Microservices
Testing MicroservicesTesting Microservices
Testing Microservices
 

More from Rossen Stoyanchev

Spring MVC 4.2: New and Noteworthy
Spring MVC 4.2: New and NoteworthySpring MVC 4.2: New and Noteworthy
Spring MVC 4.2: New and NoteworthyRossen Stoyanchev
 
Intro To Reactive Programming
Intro To Reactive ProgrammingIntro To Reactive Programming
Intro To Reactive ProgrammingRossen Stoyanchev
 
Resource Handling in Spring MVC 4.1
Resource Handling in Spring MVC 4.1Resource Handling in Spring MVC 4.1
Resource Handling in Spring MVC 4.1Rossen Stoyanchev
 
Spring 3.1 Features Worth Knowing About
Spring 3.1 Features Worth Knowing AboutSpring 3.1 Features Worth Knowing About
Spring 3.1 Features Worth Knowing AboutRossen Stoyanchev
 

More from Rossen Stoyanchev (6)

Reactive Web Applications
Reactive Web ApplicationsReactive Web Applications
Reactive Web Applications
 
Spring MVC 4.2: New and Noteworthy
Spring MVC 4.2: New and NoteworthySpring MVC 4.2: New and Noteworthy
Spring MVC 4.2: New and Noteworthy
 
Intro To Reactive Programming
Intro To Reactive ProgrammingIntro To Reactive Programming
Intro To Reactive Programming
 
Resource Handling in Spring MVC 4.1
Resource Handling in Spring MVC 4.1Resource Handling in Spring MVC 4.1
Resource Handling in Spring MVC 4.1
 
Spring 4 Web App
Spring 4 Web AppSpring 4 Web App
Spring 4 Web App
 
Spring 3.1 Features Worth Knowing About
Spring 3.1 Features Worth Knowing AboutSpring 3.1 Features Worth Knowing About
Spring 3.1 Features Worth Knowing About
 

Recently uploaded

Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
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
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 

Recently uploaded (20)

Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
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
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 

Testing Web Apps with Spring Framework 3.2

  • 1. Testing Web Applications with Spring 3.2 Sam Brannen, Swiftmind, @sam_brannen Rossen Stoyanchev, VMware, @rstoya05 © 2012 SpringSource, by VMware. All rights reserved
  • 3. Sam Brannen  Spring and Java Consultant @ Swiftmind  Developing Java for over 15 years  Spring Framework Core Committer since 2007  Spring Trainer  Presenter on Spring, Java, OSGi, and testing 3
  • 4. Rossen Stoyanchev  Spring Framework core committer  Focus on Spring Web  Main developer of Spring MVC Test 4
  • 5. Agenda  Spring TestContext Framework Updates  Spring MVC Test Framework  Q&A 5
  • 7. What's New in the Spring TCF?  Upgraded to JUnit 4.11 and TestNG 6.5.2  Loading WebApplicationContexts  Testing request- and session-scoped beans  Support for ApplicationContextInitializers  Loading context hierarchies (3.2.1)  And more… (see presentation from SpringOne 2GX 2012) 7
  • 8. Loading a WebApplicationContext Q: How do you tell the TestContext Framework to load a WebApplicationContext? A: Just annotate your test class with @WebAppConfiguration! 8
  • 9. @WebAppConfiguration  Denotes that the context should be a WebApplicationContext  Configures the resource path for the web app • Used by MockServletContext • Defaults to “src/main/webapp” • Paths are file-system folders, relative to the project root not classpath resources • The classpath: prefix is also supported 9
  • 13. ServletTestExecutionListener  Sets up default thread-local state via RequestContextHolder before each test method  Creates: • MockHttpServletRequest • MockHttpServletResponse • ServletWebRequest  Ensures that the MockHttpServletResponse and ServletWebRequest can be injected into the test instance  Cleans up thread-local state after each test method 13
  • 15. Web Scopes – Review  request: lifecycle tied to the current HttpServletRequest  session: lifecycle tied to the current HttpSession 15
  • 20. ApplicationContextInitializer  Introduced in Spring 3.1  Used for programmatic initialization of a ConfigurableApplicationContext  For example: • to register property sources • to activate profiles against the Environment  Configured in web.xml by specifying contextInitializerClasses via • context-param for the ContextLoaderListener • init-param for the DispatcherServlet 20
  • 22. Using Initializers in Tests  Configured in @ContextConfiguration via the initializers attribute  Inheritance can be controlled via the inheritInitializers attribute  An ApplicationContextInitializer may configure the entire context • XML resource locations or annotated classes are no longer required  Initializers are now part of the context cache key  Initializers are ordered based on Spring's Ordered interface or the @Order annotation 22
  • 23. Application Context Hierarchies  Currently only flat, non-hierarchical contexts are supported in tests.  There’s no easy way to create contexts with parent-child relationships.  But… hierarchies are supported in production.  Wouldn’t it be nice if you could test them, too?! 23
  • 24. Testing Context Hierarchies in version 3.2.2 (!)  New @ContextHierarchy annotation • used in conjunction with @ContextConfiguration  @ContextConfiguration now supports a ‘name’ attribute • for merging and overriding hierarchy configuration 24
  • 25. Single Test with Context Hierarchy 25
  • 26. Class and Context Hierarchies 26
  • 27. Built-in Spring MVC Test Support 27
  • 28. Overview  Dedicated support for testing Spring MVC applications  Fluent API  Very easy to write  Includes client and server-side support  Servlet container not required 28
  • 29. In More Detail  Included in spring-test module of Spring Framework 3.2  Builds on • TestContext framework for loading Spring MVC configuration • MockHttpServletRequest/Response and other “mock” types  Server-side tests involve DispatcherServlet  Client-side REST testing for code using RestTemplate 29
  • 30. Spring MVC Test History  Evolved as independent project on Github • https://github.com/SpringSource/spring-test-mvc  Now folded into Spring Framework 3.2  Former project still supports Spring Framework 3.1 30
  • 32. A Note On Fluent API Usage  Requires static imports import static MockMvcRequestBuilders.get; import static MockMvcResultMatchers.status; mockMvc.perform(get(“/foo”)).andExpect(status().isOk())  Add as “favorite static members” in Eclipse preferences • Java -> Editor -> Content Assist -> Favorites 32
  • 33. Server-Side Test Recap  Actual Spring MVC configuration loaded  MockHttpServletRequest prepared  Executed via DispatcherServlet  Assertions applied on the resulting MockHttpServletResponse 33
  • 34. Integration Or Unit Testing?  Mock request/response types, no Servlet container  However.. • DispatcherServlet + actual Spring MVC configuration used  Hence.. • Not full end-to-end testing, i.e. does not replace Selenium • However provides full confidence in Spring MVC web layer  In short, integration testing for Spring MVC • Don't get too caught up in terminology! 34
  • 35. Strategy For Testing  Focus on testing the Spring MVC web layer alone • Inject controllers with mock services or database repositories  Thoroughly test Spring MVC • Including code and configuration  Separate from lower layer integration tests • E.g. database tests 35
  • 36. Declaring A Mock Dependency  Since we're loading actual Spring MVC config  Need to declare mock dependencies <bean class="org.mockito.Mockito" factory-method="mock"> <constructor-arg value="org.example.FooDao"/> </bean>  Then simply inject the mock instance into the test class • Via @Autowired • Set up and reset via @Before, @Test, and @After methods 36
  • 37. What Can Be Tested?  Response status, headers, and content • Focus on asserting these first...  Spring MVC and Servlet specific results • Model, flash, session, request attributes • Mapped controller method and interceptors • Resolved exceptions  Various options for asserting the response body • JSONPath, XPath, XMLUnit • Hamcrest matchers 37
  • 38. What About the View Layer?  All view templating technologies will work • Freemarker/Velocity, Thymeleaf, JSON, XML, PDF, etc.  Except for JSPs (no Servlet container!) • You can however assert the selected JSP  No redirecting and forwarding • You can however assert the redirected or forwarded URL  Also of interest • HTML Unit / Selenium Driver integration (experimental) • https://github.com/SpringSource/spring-test-mvc-htmlunit 38
  • 39. Useful Option For Debugging  Print all details to the console, i.e. System.out mockMvc.perform("/foo") .andDo(print()) .andExpect(status().Ok()) 39
  • 40. “Standalone” Setup  No Spring configuration is loaded  Test one controller at a time  Just provide the controller instance 40
  • 42. Tests with Servlet Filters 42
  • 43. Re-use Request Properties and Expectations 43
  • 44. Direct Access to the Underlying MvcResult 44
  • 46. Client-Side REST Test Recap  An instance of RestTemplate configured with custom ClientHttpRequestFactory  Records and asserts expected requests • Instead of executing them  Code using RestTemlpate can now be invoked  Use verify() to assert all expectations were executed 46
  • 47. Acknowledgements The Spring MVC Test support draws inspiration from similar test framework in Spring Web Services 47
  • 48. Further Resources: Spring MVC Test  Reference doc chapter on Spring MVC Test  Sample tests in the framework source code • https://github.com/SpringSource/spring-framework/tree/3.2.x/spring-test- mvc/src/test/java/org/springframework/test/web/servlet/samples • https://github.com/SpringSource/spring-framework/tree/3.2.x/spring-test- mvc/src/test/java/org/springframework/test/web/client/samples  Tests in spring-mvc-showcase • https://github.com/SpringSource/spring-mvc-showcase 48
  • 49. Further Resources Cont'd  Spring Framework • http://www.springsource.org/spring-framework • Reference manual and Javadoc  Forums • http://forum.springframework.org  JIRA • http://jira.springframework.org  GitHub • https://github.com/SpringSource/spring-framework 49
  • 50. Blogs  SpringSource Team Blog • http://blog.springsource.com/  Swiftmind Team Blog • http://www.swiftmind.com/blog/ 50
  • 51. Q&A  Sam Brannen • twitter: @sam_brannen • www.slideshare.net/sbrannen • www.swiftmind.com  Rossen Stoyanchev • twitter: @rstoya05 51