SlideShare a Scribd company logo
1 of 56
Download to read offline
Testing Spring MVC and REST
Web Applications
Sam Brannen
@sam_brannen
Spring eXchange | London, England | 15 November 2013
2
Sam Brannen
•  Spring and Java Consultant @ Swiftmind
•  Java Developer for over 15 years
•  Spring Framework Core Committer since 2007
•  Spring Trainer
•  Presenter on Spring, Java, OSGi, and testing
3
Swiftmind
Your experts for Enterprise Java
Areas of expertise
•  Spring *
•  Java EE
•  OSGi
•  Agile Methodologies
•  Software Engineering Best Practices
Where you find us
•  Zurich, Switzerland
•  @swiftmind
•  http://www.swiftmind.com
4
A Show of Hands…
5
Agenda
•  Spring TestContext Framework Updates
•  Spring MVC Test Framework
•  Q & A
6
Spring TestContext Framework Updates
7
What’s New in the Spring TCF?
•  Upgraded to JUnit 4.11 and TestNG 6.5.2
•  Loading a WebApplicationContext
•  Testing request- and session-scoped beans
•  Support for ApplicationContextInitializer
•  Loading context hierarchies (3.2.2)
•  Meta-annotation support for tests (4.0)
8
Loading a WebApplicationContext
Q: How do you tell the TestContext Framework to load a
WebApplicationContext?
A: Just annotate your test class with @WebAppConfiguration!
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 class path resources
–  The classpath: prefix is also supported
10
@WAC – Default Values
11
@WAC – Default Resource Types
12
@WAC – Overrides
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
14
Example: Injecting Mocks
15
Web Scopes – Review
request: lifecycle tied to the current HttpServletRequest
session: lifecycle tied to the current HttpSession
16
Example: Request-scoped Bean Config
17
Example: Request-scoped Bean Test
18
Example: Session-scoped Bean Config
19
Example: Session-scoped Bean Test
20
ApplicationContextInitalizer
•  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
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
Example: Multiple Initializers
23
Application Context Hierarchies
•  Traditionally only flat, non-hierarchical contexts were
supported in tests.
•  There was 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?!
24
Testing Context Hierarchies in 3.2.2
•  New @ContextHierarchy annotation
–  Used in conjunction with @ContextConfiguration
•  @ContextConfiguration now supports a ‘name’ attribute
–  for merging and overriding hierarchy configuration
25
Single Test with Context Hierarchy
26
Class and Context Hierarchies
27
Testing Changes in 4.0
Gone:
–  JUnit 3.8 support
–  @ExpectedException	

–  @NotTransactional	
–  SimpleJdbcTestUtils	
	
Updated:
–  Servlet API mocks
–  Spring MVC Test framework
28
New Testing Features in 4.0
•  SocketUtils	
–  scan for UDP & TCP ports
	
•  ActiveProfilesResolver	
–  alternative to static profile strings
–  set via new resolver attribute in @ActiveProfiles
•  Meta-annotation support for tests
29
Meta-annotations in Tests
@ContextConfiguration({	
"/app-config.xml", "/test-config.xml"	
})	
@ActiveProfiles("dev")	
@Transactional	
@Retention(RetentionPolicy.RUNTIME)	
public @interface TransactionalTest { }	
	
	
@TransactionalTest	
@RunWith(SpringJUnit4ClassRunner.class)	
public class UserRepositoryIntegrationTests { /* ... */ }
30
Spring MVC Test Framework
31
What is Spring MVC Test?
•  Dedicated support for testing Spring MVC applications
•  Fluent API
•  Very easy to write
•  Includes client and server-side support
•  Servlet container not required
32
Details
•  Included in spring-test module of Spring Framework 3.2
•  Builds on
–  TestContext framework for loading Spring MVC
configuration
–  MockHttpServlet[Request|Response] and other mock
types
•  Server-side tests involve DispatcherServlet
•  Client-side REST testing for code using RestTemplate
33
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
34
Server-side Example
35
A Note of 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
36
Server-side Test Recap
•  Actual Spring MVC configuration loaded
•  MockHttpServletRequest prepared
•  Executed via DispatcherServlet
•  Assertions applied on the resulting
MockHttpServletResponse
37
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; 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!
38
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., data access tests
39
Declaring a Mocked Dependency
•  Since we're loading actual Spring MVC config …
•  First declare mock dependency:
	
<bean class="org.mockito.Mockito" factory-method="mock">	
<constructor-arg value="org.example.FooRepository"/>	
</bean> 	
•  Then simply inject the mock instance into the test class
–  Via @Autowired or @Inject
–  Set up and reset via @Before, @Test, and @After methods
40
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
41
What about the view layer?
•  All view templating technologies will work
–  Freemarker, Velocity, Thymeleaf, JSON, XML, PDF, etc.
•  Except for JSPs (no Servlet container!)
–  But you can assert which JSP was selected
•  No redirecting and forwarding
–  But you can assert the redirected or forwarded URL
•  Also of interest
–  HTML Unit / Selenium Driver integration (experimental)
–  https://github.com/SpringSource/spring-test-mvc-
htmlunit
42
Useful Option for Debugging
Print all details to the console, i.e. System.out
mockMvc.perform("/foo")	
.andDo(print())	
.andExpect(status().isOk())
43
“Standalone” Setup
•  No Spring configuration is loaded
•  Test one controller at a time
•  Just provide the controller instance
44
“Standalone” Setup Example
45
Test with Servlet Filters
46
Re-use Request Props & Expectations
47
Direct Access to underlying MvcResult
48
Client-side REST Example
49
Client-side REST Test Recap
•  An instance of RestTemplate configured with custom
ClientHttpRequestFactory
•  Records and asserts expected requests
–  Instead of executing them
•  Code using RestTemplate can now be invoked
•  Use verify() to assert all expectations were executed
50
Acknowledgements
The Spring MVC Test support draws inspiration
from a similar test framework in Spring Web
Services.
51
In Closing…
52
Special Thanks to…
Rossen Stoyanchev
… for permitting reuse of his slides on Spring MVC Test!
53
Spring Resources
•  Spring Framework
–  http://projects.spring.io/spring-framework
•  Spring Forums
–  http://forum.spring.io
•  Spring JIRA
–  http://jira.springsource.org
•  Spring on GitHub
–  https://github.com/spring-projects/spring-framework
54
Spring MVC Test Resources
•  Blog post
–  http://bit.ly/QCKMzh
•  Samples
–  https://github.com/spring-projects/spring-mvc-showcase
–  http://bit.ly/VN1bPw … sample server tests
–  http://bit.ly/13koRQP … sample client tests
•  Reference documentation
–  http://bit.ly/SmUtD6
55
Blogs
•  Swiftmind Team Blog
–  http://www.swiftmind.com/blog
•  SpringSource Team Blog
–  http://spring.io/blog
56
Q & A
Sam Brannen
@sam_brannen
www.slideshare.net/sbrannen
www.swiftmind.com

More Related Content

What's hot

JUnit 5 - from Lambda to Alpha and beyond
JUnit 5 - from Lambda to Alpha and beyondJUnit 5 - from Lambda to Alpha and beyond
JUnit 5 - from Lambda to Alpha and beyondSam Brannen
 
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
 
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
 
Apache maven, a software project management tool
Apache maven, a software project management toolApache maven, a software project management tool
Apache maven, a software project management toolRenato Primavera
 
Advanced Selenium Workshop
Advanced Selenium WorkshopAdvanced Selenium Workshop
Advanced Selenium WorkshopClever Moe
 
Selenium - Introduction
Selenium - IntroductionSelenium - Introduction
Selenium - IntroductionAmr E. Mohamed
 
San Jose Selenium Meet-up PushToTest TestMaker Presentation
San Jose Selenium Meet-up PushToTest TestMaker PresentationSan Jose Selenium Meet-up PushToTest TestMaker Presentation
San Jose Selenium Meet-up PushToTest TestMaker PresentationClever Moe
 
Infinum Android Talks #17 - Testing your Android applications by Ivan Kust
Infinum Android Talks #17 - Testing your Android applications by Ivan KustInfinum Android Talks #17 - Testing your Android applications by Ivan Kust
Infinum Android Talks #17 - Testing your Android applications by Ivan KustInfinum
 
Selenium XPath Performance Problems in IE
Selenium XPath Performance Problems in IESelenium XPath Performance Problems in IE
Selenium XPath Performance Problems in IEClever Moe
 
Selenium Basics Tutorial
Selenium Basics TutorialSelenium Basics Tutorial
Selenium Basics TutorialClever Moe
 
Android Meetup Slovenija #3 - Testing with Robolectric by Ivan Kust
Android Meetup Slovenija #3 - Testing with Robolectric by Ivan KustAndroid Meetup Slovenija #3 - Testing with Robolectric by Ivan Kust
Android Meetup Slovenija #3 - Testing with Robolectric by Ivan KustInfinum
 
PHP Unit Testing in Yii
PHP Unit Testing in YiiPHP Unit Testing in Yii
PHP Unit Testing in YiiIlPeach
 
Selenium Tutorial
Selenium TutorialSelenium Tutorial
Selenium Tutorialprad_123
 
Selenium webdriver interview questions and answers
Selenium webdriver interview questions and answersSelenium webdriver interview questions and answers
Selenium webdriver interview questions and answersITeLearn
 
Springboot introduction
Springboot introductionSpringboot introduction
Springboot introductionSagar Verma
 
Selenium notes
Selenium notesSelenium notes
Selenium noteswholcomb
 
Acceptance testing in php with Codeception - Techmeetup Edinburgh
Acceptance testing in php with Codeception - Techmeetup EdinburghAcceptance testing in php with Codeception - Techmeetup Edinburgh
Acceptance testing in php with Codeception - Techmeetup EdinburghEngineor
 

What's hot (20)

Spring Test Framework
Spring Test FrameworkSpring Test Framework
Spring Test Framework
 
JUnit 5 - from Lambda to Alpha and beyond
JUnit 5 - from Lambda to Alpha and beyondJUnit 5 - from Lambda to Alpha and beyond
JUnit 5 - from Lambda to Alpha and beyond
 
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
 
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
 
Apache maven, a software project management tool
Apache maven, a software project management toolApache maven, a software project management tool
Apache maven, a software project management tool
 
Advanced Selenium Workshop
Advanced Selenium WorkshopAdvanced Selenium Workshop
Advanced Selenium Workshop
 
Selenium - Introduction
Selenium - IntroductionSelenium - Introduction
Selenium - Introduction
 
San Jose Selenium Meet-up PushToTest TestMaker Presentation
San Jose Selenium Meet-up PushToTest TestMaker PresentationSan Jose Selenium Meet-up PushToTest TestMaker Presentation
San Jose Selenium Meet-up PushToTest TestMaker Presentation
 
Infinum Android Talks #17 - Testing your Android applications by Ivan Kust
Infinum Android Talks #17 - Testing your Android applications by Ivan KustInfinum Android Talks #17 - Testing your Android applications by Ivan Kust
Infinum Android Talks #17 - Testing your Android applications by Ivan Kust
 
Selenium Handbook
Selenium HandbookSelenium Handbook
Selenium Handbook
 
Selenium With Spices
Selenium With SpicesSelenium With Spices
Selenium With Spices
 
Selenium XPath Performance Problems in IE
Selenium XPath Performance Problems in IESelenium XPath Performance Problems in IE
Selenium XPath Performance Problems in IE
 
Selenium Basics Tutorial
Selenium Basics TutorialSelenium Basics Tutorial
Selenium Basics Tutorial
 
Android Meetup Slovenija #3 - Testing with Robolectric by Ivan Kust
Android Meetup Slovenija #3 - Testing with Robolectric by Ivan KustAndroid Meetup Slovenija #3 - Testing with Robolectric by Ivan Kust
Android Meetup Slovenija #3 - Testing with Robolectric by Ivan Kust
 
PHP Unit Testing in Yii
PHP Unit Testing in YiiPHP Unit Testing in Yii
PHP Unit Testing in Yii
 
Selenium Tutorial
Selenium TutorialSelenium Tutorial
Selenium Tutorial
 
Selenium webdriver interview questions and answers
Selenium webdriver interview questions and answersSelenium webdriver interview questions and answers
Selenium webdriver interview questions and answers
 
Springboot introduction
Springboot introductionSpringboot introduction
Springboot introduction
 
Selenium notes
Selenium notesSelenium notes
Selenium notes
 
Acceptance testing in php with Codeception - Techmeetup Edinburgh
Acceptance testing in php with Codeception - Techmeetup EdinburghAcceptance testing in php with Codeception - Techmeetup Edinburgh
Acceptance testing in php with Codeception - Techmeetup Edinburgh
 

Similar to Testing Spring MVC and REST APIs with the Spring Test Framework

Spring Framework 3.2 - What's New
Spring Framework 3.2 - What's NewSpring Framework 3.2 - What's New
Spring Framework 3.2 - What's NewSam 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
 
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
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework Serhat Can
 
Effective out-of-container Integration Testing
Effective out-of-container Integration TestingEffective out-of-container Integration Testing
Effective out-of-container Integration TestingSam 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
 
The Meteor Framework
The Meteor FrameworkThe Meteor Framework
The Meteor FrameworkDamien Magoni
 
Spring Framework 4.0 to 4.1
Spring Framework 4.0 to 4.1Spring Framework 4.0 to 4.1
Spring Framework 4.0 to 4.1Sam Brannen
 
Integrating Servlets and JSP (The MVC Architecture)
Integrating Servlets and JSP  (The MVC Architecture)Integrating Servlets and JSP  (The MVC Architecture)
Integrating Servlets and JSP (The MVC Architecture)Amit Ranjan
 
Testing Microservices
Testing MicroservicesTesting Microservices
Testing MicroservicesAnil Allewar
 
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
 
Case Study: Migrating Hyperic from EJB to Spring from JBoss to Apache Tomcat
Case Study: Migrating Hyperic from EJB to Spring from JBoss to Apache TomcatCase Study: Migrating Hyperic from EJB to Spring from JBoss to Apache Tomcat
Case Study: Migrating Hyperic from EJB to Spring from JBoss to Apache TomcatVMware Hyperic
 
Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010
Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010
Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010Arun Gupta
 
Cloud compiler - Minor Project by students of CBPGEC
Cloud compiler - Minor Project by students of CBPGEC  Cloud compiler - Minor Project by students of CBPGEC
Cloud compiler - Minor Project by students of CBPGEC vipin kumar
 
Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot IntroductionJeevesh Pandey
 

Similar to Testing Spring MVC and REST APIs with the Spring Test Framework (20)

Spring Framework 3.2 - What's New
Spring Framework 3.2 - What's NewSpring Framework 3.2 - What's New
Spring Framework 3.2 - What's New
 
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
 
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
 
Next stop: Spring 4
Next stop: Spring 4Next stop: Spring 4
Next stop: Spring 4
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
Effective out-of-container Integration Testing
Effective out-of-container Integration TestingEffective out-of-container Integration Testing
Effective out-of-container Integration Testing
 
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
 
The Meteor Framework
The Meteor FrameworkThe Meteor Framework
The Meteor Framework
 
Spring Framework 4.0 to 4.1
Spring Framework 4.0 to 4.1Spring Framework 4.0 to 4.1
Spring Framework 4.0 to 4.1
 
Integrating Servlets and JSP (The MVC Architecture)
Integrating Servlets and JSP  (The MVC Architecture)Integrating Servlets and JSP  (The MVC Architecture)
Integrating Servlets and JSP (The MVC Architecture)
 
Testing Microservices
Testing MicroservicesTesting Microservices
Testing Microservices
 
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
 
Case Study: Migrating Hyperic from EJB to Spring from JBoss to Apache Tomcat
Case Study: Migrating Hyperic from EJB to Spring from JBoss to Apache TomcatCase Study: Migrating Hyperic from EJB to Spring from JBoss to Apache Tomcat
Case Study: Migrating Hyperic from EJB to Spring from JBoss to Apache Tomcat
 
Wt unit 3 server side technology
Wt unit 3 server side technologyWt unit 3 server side technology
Wt unit 3 server side technology
 
Wt unit 3 server side technology
Wt unit 3 server side technologyWt unit 3 server side technology
Wt unit 3 server side technology
 
Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010
Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010
Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010
 
Cloud compiler - Minor Project by students of CBPGEC
Cloud compiler - Minor Project by students of CBPGEC  Cloud compiler - Minor Project by students of CBPGEC
Cloud compiler - Minor Project by students of CBPGEC
 
Test automation proposal
Test automation proposalTest automation proposal
Test automation proposal
 
Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot Introduction
 

More from Sam Brannen

Testing with Spring, AOT, GraalVM, and JUnit 5 - Spring I/O 2023
Testing with Spring, AOT, GraalVM, and JUnit 5 - Spring I/O 2023Testing with Spring, AOT, GraalVM, and JUnit 5 - Spring I/O 2023
Testing with Spring, AOT, GraalVM, and JUnit 5 - Spring I/O 2023Sam Brannen
 
Testing with JUnit 5 and Spring - Spring I/O 2022
Testing with JUnit 5 and Spring - Spring I/O 2022Testing with JUnit 5 and Spring - Spring I/O 2022
Testing with JUnit 5 and Spring - Spring I/O 2022Sam Brannen
 
JUnit 5: What's New and What's Coming - Spring I/O 2019
JUnit 5: What's New and What's Coming - Spring I/O 2019JUnit 5: What's New and What's Coming - Spring I/O 2019
JUnit 5: What's New and What's Coming - Spring I/O 2019Sam Brannen
 
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 JVMSam Brannen
 
Composable Software Architecture with Spring
Composable Software Architecture with SpringComposable Software Architecture with Spring
Composable Software Architecture with SpringSam Brannen
 
Spring Framework 4.0 - The Next Generation - Soft-Shake 2013
Spring Framework 4.0 - The Next Generation - Soft-Shake 2013Spring Framework 4.0 - The Next Generation - Soft-Shake 2013
Spring Framework 4.0 - The Next Generation - Soft-Shake 2013Sam Brannen
 
Spring 3.1 and MVC Testing Support - 4Developers
Spring 3.1 and MVC Testing Support - 4DevelopersSpring 3.1 and MVC Testing Support - 4Developers
Spring 3.1 and MVC Testing Support - 4DevelopersSam Brannen
 
Effective out-of-container Integration Testing - 4Developers
Effective out-of-container Integration Testing - 4DevelopersEffective out-of-container Integration Testing - 4Developers
Effective out-of-container Integration Testing - 4DevelopersSam Brannen
 
Spring 3.1 to 3.2 in a Nutshell - SDC2012
Spring 3.1 to 3.2 in a Nutshell - SDC2012Spring 3.1 to 3.2 in a Nutshell - SDC2012
Spring 3.1 to 3.2 in a Nutshell - SDC2012Sam Brannen
 
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 3.1 in a Nutshell
Spring 3.1 in a NutshellSpring 3.1 in a Nutshell
Spring 3.1 in a NutshellSam Brannen
 
Spring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSpring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSam Brannen
 
What's New in Spring 3.0
What's New in Spring 3.0What's New in Spring 3.0
What's New in Spring 3.0Sam Brannen
 
Modular Web Applications with OSGi
Modular Web Applications with OSGiModular Web Applications with OSGi
Modular Web Applications with OSGiSam Brannen
 
Enterprise Applications With OSGi and SpringSource dm Server
Enterprise Applications With OSGi and SpringSource dm ServerEnterprise Applications With OSGi and SpringSource dm Server
Enterprise Applications With OSGi and SpringSource dm ServerSam Brannen
 

More from Sam Brannen (15)

Testing with Spring, AOT, GraalVM, and JUnit 5 - Spring I/O 2023
Testing with Spring, AOT, GraalVM, and JUnit 5 - Spring I/O 2023Testing with Spring, AOT, GraalVM, and JUnit 5 - Spring I/O 2023
Testing with Spring, AOT, GraalVM, and JUnit 5 - Spring I/O 2023
 
Testing with JUnit 5 and Spring - Spring I/O 2022
Testing with JUnit 5 and Spring - Spring I/O 2022Testing with JUnit 5 and Spring - Spring I/O 2022
Testing with JUnit 5 and Spring - Spring I/O 2022
 
JUnit 5: What's New and What's Coming - Spring I/O 2019
JUnit 5: What's New and What's Coming - Spring I/O 2019JUnit 5: What's New and What's Coming - Spring I/O 2019
JUnit 5: What's New and What's Coming - Spring I/O 2019
 
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
 
Composable Software Architecture with Spring
Composable Software Architecture with SpringComposable Software Architecture with Spring
Composable Software Architecture with Spring
 
Spring Framework 4.0 - The Next Generation - Soft-Shake 2013
Spring Framework 4.0 - The Next Generation - Soft-Shake 2013Spring Framework 4.0 - The Next Generation - Soft-Shake 2013
Spring Framework 4.0 - The Next Generation - Soft-Shake 2013
 
Spring 3.1 and MVC Testing Support - 4Developers
Spring 3.1 and MVC Testing Support - 4DevelopersSpring 3.1 and MVC Testing Support - 4Developers
Spring 3.1 and MVC Testing Support - 4Developers
 
Effective out-of-container Integration Testing - 4Developers
Effective out-of-container Integration Testing - 4DevelopersEffective out-of-container Integration Testing - 4Developers
Effective out-of-container Integration Testing - 4Developers
 
Spring 3.1 to 3.2 in a Nutshell - SDC2012
Spring 3.1 to 3.2 in a Nutshell - SDC2012Spring 3.1 to 3.2 in a Nutshell - SDC2012
Spring 3.1 to 3.2 in a Nutshell - SDC2012
 
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 3.1 in a Nutshell
Spring 3.1 in a NutshellSpring 3.1 in a Nutshell
Spring 3.1 in a Nutshell
 
Spring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSpring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. REST
 
What's New in Spring 3.0
What's New in Spring 3.0What's New in Spring 3.0
What's New in Spring 3.0
 
Modular Web Applications with OSGi
Modular Web Applications with OSGiModular Web Applications with OSGi
Modular Web Applications with OSGi
 
Enterprise Applications With OSGi and SpringSource dm Server
Enterprise Applications With OSGi and SpringSource dm ServerEnterprise Applications With OSGi and SpringSource dm Server
Enterprise Applications With OSGi and SpringSource dm Server
 

Recently uploaded

Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfLivetecs LLC
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfStefano Stabellini
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noidabntitsolutionsrishis
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 

Recently uploaded (20)

Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdf
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdf
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
Advantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your BusinessAdvantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your Business
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 

Testing Spring MVC and REST APIs with the Spring Test Framework

  • 1. Testing Spring MVC and REST Web Applications Sam Brannen @sam_brannen Spring eXchange | London, England | 15 November 2013
  • 2. 2 Sam Brannen •  Spring and Java Consultant @ Swiftmind •  Java Developer for over 15 years •  Spring Framework Core Committer since 2007 •  Spring Trainer •  Presenter on Spring, Java, OSGi, and testing
  • 3. 3 Swiftmind Your experts for Enterprise Java Areas of expertise •  Spring * •  Java EE •  OSGi •  Agile Methodologies •  Software Engineering Best Practices Where you find us •  Zurich, Switzerland •  @swiftmind •  http://www.swiftmind.com
  • 4. 4 A Show of Hands…
  • 5. 5 Agenda •  Spring TestContext Framework Updates •  Spring MVC Test Framework •  Q & A
  • 7. 7 What’s New in the Spring TCF? •  Upgraded to JUnit 4.11 and TestNG 6.5.2 •  Loading a WebApplicationContext •  Testing request- and session-scoped beans •  Support for ApplicationContextInitializer •  Loading context hierarchies (3.2.2) •  Meta-annotation support for tests (4.0)
  • 8. 8 Loading a WebApplicationContext Q: How do you tell the TestContext Framework to load a WebApplicationContext? A: Just annotate your test class with @WebAppConfiguration!
  • 9. 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 class path resources –  The classpath: prefix is also supported
  • 11. 11 @WAC – Default Resource Types
  • 13. 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
  • 15. 15 Web Scopes – Review request: lifecycle tied to the current HttpServletRequest session: lifecycle tied to the current HttpSession
  • 20. 20 ApplicationContextInitalizer •  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
  • 21. 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
  • 23. 23 Application Context Hierarchies •  Traditionally only flat, non-hierarchical contexts were supported in tests. •  There was 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?!
  • 24. 24 Testing Context Hierarchies in 3.2.2 •  New @ContextHierarchy annotation –  Used in conjunction with @ContextConfiguration •  @ContextConfiguration now supports a ‘name’ attribute –  for merging and overriding hierarchy configuration
  • 25. 25 Single Test with Context Hierarchy
  • 26. 26 Class and Context Hierarchies
  • 27. 27 Testing Changes in 4.0 Gone: –  JUnit 3.8 support –  @ExpectedException –  @NotTransactional –  SimpleJdbcTestUtils Updated: –  Servlet API mocks –  Spring MVC Test framework
  • 28. 28 New Testing Features in 4.0 •  SocketUtils –  scan for UDP & TCP ports •  ActiveProfilesResolver –  alternative to static profile strings –  set via new resolver attribute in @ActiveProfiles •  Meta-annotation support for tests
  • 29. 29 Meta-annotations in Tests @ContextConfiguration({ "/app-config.xml", "/test-config.xml" }) @ActiveProfiles("dev") @Transactional @Retention(RetentionPolicy.RUNTIME) public @interface TransactionalTest { } @TransactionalTest @RunWith(SpringJUnit4ClassRunner.class) public class UserRepositoryIntegrationTests { /* ... */ }
  • 30. 30 Spring MVC Test Framework
  • 31. 31 What is Spring MVC Test? •  Dedicated support for testing Spring MVC applications •  Fluent API •  Very easy to write •  Includes client and server-side support •  Servlet container not required
  • 32. 32 Details •  Included in spring-test module of Spring Framework 3.2 •  Builds on –  TestContext framework for loading Spring MVC configuration –  MockHttpServlet[Request|Response] and other mock types •  Server-side tests involve DispatcherServlet •  Client-side REST testing for code using RestTemplate
  • 33. 33 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
  • 35. 35 A Note of 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
  • 36. 36 Server-side Test Recap •  Actual Spring MVC configuration loaded •  MockHttpServletRequest prepared •  Executed via DispatcherServlet •  Assertions applied on the resulting MockHttpServletResponse
  • 37. 37 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; 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!
  • 38. 38 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., data access tests
  • 39. 39 Declaring a Mocked Dependency •  Since we're loading actual Spring MVC config … •  First declare mock dependency: <bean class="org.mockito.Mockito" factory-method="mock"> <constructor-arg value="org.example.FooRepository"/> </bean> •  Then simply inject the mock instance into the test class –  Via @Autowired or @Inject –  Set up and reset via @Before, @Test, and @After methods
  • 40. 40 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
  • 41. 41 What about the view layer? •  All view templating technologies will work –  Freemarker, Velocity, Thymeleaf, JSON, XML, PDF, etc. •  Except for JSPs (no Servlet container!) –  But you can assert which JSP was selected •  No redirecting and forwarding –  But you can assert the redirected or forwarded URL •  Also of interest –  HTML Unit / Selenium Driver integration (experimental) –  https://github.com/SpringSource/spring-test-mvc- htmlunit
  • 42. 42 Useful Option for Debugging Print all details to the console, i.e. System.out mockMvc.perform("/foo") .andDo(print()) .andExpect(status().isOk())
  • 43. 43 “Standalone” Setup •  No Spring configuration is loaded •  Test one controller at a time •  Just provide the controller instance
  • 46. 46 Re-use Request Props & Expectations
  • 47. 47 Direct Access to underlying MvcResult
  • 49. 49 Client-side REST Test Recap •  An instance of RestTemplate configured with custom ClientHttpRequestFactory •  Records and asserts expected requests –  Instead of executing them •  Code using RestTemplate can now be invoked •  Use verify() to assert all expectations were executed
  • 50. 50 Acknowledgements The Spring MVC Test support draws inspiration from a similar test framework in Spring Web Services.
  • 52. 52 Special Thanks to… Rossen Stoyanchev … for permitting reuse of his slides on Spring MVC Test!
  • 53. 53 Spring Resources •  Spring Framework –  http://projects.spring.io/spring-framework •  Spring Forums –  http://forum.spring.io •  Spring JIRA –  http://jira.springsource.org •  Spring on GitHub –  https://github.com/spring-projects/spring-framework
  • 54. 54 Spring MVC Test Resources •  Blog post –  http://bit.ly/QCKMzh •  Samples –  https://github.com/spring-projects/spring-mvc-showcase –  http://bit.ly/VN1bPw … sample server tests –  http://bit.ly/13koRQP … sample client tests •  Reference documentation –  http://bit.ly/SmUtD6
  • 55. 55 Blogs •  Swiftmind Team Blog –  http://www.swiftmind.com/blog •  SpringSource Team Blog –  http://spring.io/blog
  • 56. 56 Q & A Sam Brannen @sam_brannen www.slideshare.net/sbrannen www.swiftmind.com