This document provides an overview and examples of testing web applications built with the Spring framework. It discusses testing Spring controllers with pure unit tests using JUnit and Mockito. It also introduces the Spring MVC test framework for server-side integration testing of Spring MVC components without requiring a running servlet container. Examples are given of testing controller methods, request mappings, exceptions, and views using the MockMvc API to build and perform mock requests and assert the response.
Testing Spring MVC and REST Web ApplicationsSam Brannen
The Spring Team has innovated extensively around testing in the past, and this innovation continues today. One of the most exciting recent additions to Spring's testing support is Spring MVC Test. What makes it so interesting is the comprehensive support for testing web applications and context hierarchies with the Spring TestContext Framework as well as comprehensive support for out-of-container Spring MVC and REST integration testing.
Join core Spring Framework committer Sam Brannen to see these new Spring Web testing features in action and learn how to speed up your development-test lifecycle.
Presented on Feb 21, 2013 as part of a springsource.org webinar. A video of the presentation will be available 2 weeks later at http://www.youtube.com/springsourcedev.
The Spring Framework has always embraced testing as a first class citizen. Spring-based components should be modular, easy to wire together via dependency injection, and therefore easy to test. In fact, when well designed following a POJO programming model, a component in a Spring application can be unit tested without using Spring at all. And when you take the step toward developing integration tests, Spring's testing support is there to make your job easy.
Join Spring Test component lead Sam Brannen in this talk to learn about the basics for Spring's unit and integration testing support. This talk will provide attendees an overview of the following topics: unit testing without Spring, integration testing with Spring, loading application contexts (with and without context hierarchies), injecting dependencies into tests, transaction management for tests, SQL script execution, testing Spring MVC and REST web applications, and more.
This webinar by Oleksandr Navka (Lead Software Engineer, Consultant, GlobalLogic) was delivered at Java Community Webinar #2 on September 17, 2020.
Webinar agenda:
- tools for testing,
- features of creating a context for testing Spring-applications,
- context caching to speed up integration testing
More details and presentation: https://www.globallogic.com/ua/about/events/java-community-webinar-2/
The Spring Framework has undergone a lot of innovation in the 4.0 and 4.1 releases, and so has its testing support. Join Spring Test component lead Sam Brannen in this talk to discover what's new in Spring's testing support in 4.0 through 4.1.
This talk will provide attendees an overview of what's been deprecated, what's changed, and what's been introduced in Spring's testing support over the last two years, with real life examples and tips for best practices. Highlights include using SocketUtils to scan for free TCP & UDP server ports, the ActiveProfilesResolver API, meta-annotation support for test annotations including attribute overrides, best practices with TestNG, using Groovy scripts to configure an ApplicationContext for integration tests, improvements to SQL script execution and embedded databases, the new TestContext framework bootstrap strategy, programmatic transaction management in tests, and more.
Spring Framework 4.1 is the latest release of the popular open source application framework for Java developers with continued innovation for Java SE 8 and enterprise Java. In this presentation core Spring committer Sam Brannen will provide attendees an overview of the new enterprise features in the framework as well as new programming models and testing features.
Specifically, this talk will cover support for annotation-driven JMS listeners, JMS 2.0's shared subscriptions, JCache (JSR-107) annotations, a compiler mode for the Spring Expression Language (SpEL), flexible resolution and transformation of static web resources, and Web MVC support for Groovy markup templates.
The presentation also provides an overview of Spring 4.1's refinements in other areas, for example: Java 8's Optional type for injection points, declarative MVC view resolution, Jackson's JsonView, WebSocket scope, SockJS client support, declarative SQL scripts and programmatic transactions in the TestContext framework, integration testing with Groovy scripts, and more.
Testing Spring MVC and REST Web ApplicationsSam Brannen
The Spring Team has innovated extensively around testing in the past, and this innovation continues today. One of the most exciting recent additions to Spring's testing support is Spring MVC Test. What makes it so interesting is the comprehensive support for testing web applications and context hierarchies with the Spring TestContext Framework as well as comprehensive support for out-of-container Spring MVC and REST integration testing.
Join core Spring Framework committer Sam Brannen to see these new Spring Web testing features in action and learn how to speed up your development-test lifecycle.
Presented on Feb 21, 2013 as part of a springsource.org webinar. A video of the presentation will be available 2 weeks later at http://www.youtube.com/springsourcedev.
The Spring Framework has always embraced testing as a first class citizen. Spring-based components should be modular, easy to wire together via dependency injection, and therefore easy to test. In fact, when well designed following a POJO programming model, a component in a Spring application can be unit tested without using Spring at all. And when you take the step toward developing integration tests, Spring's testing support is there to make your job easy.
Join Spring Test component lead Sam Brannen in this talk to learn about the basics for Spring's unit and integration testing support. This talk will provide attendees an overview of the following topics: unit testing without Spring, integration testing with Spring, loading application contexts (with and without context hierarchies), injecting dependencies into tests, transaction management for tests, SQL script execution, testing Spring MVC and REST web applications, and more.
This webinar by Oleksandr Navka (Lead Software Engineer, Consultant, GlobalLogic) was delivered at Java Community Webinar #2 on September 17, 2020.
Webinar agenda:
- tools for testing,
- features of creating a context for testing Spring-applications,
- context caching to speed up integration testing
More details and presentation: https://www.globallogic.com/ua/about/events/java-community-webinar-2/
The Spring Framework has undergone a lot of innovation in the 4.0 and 4.1 releases, and so has its testing support. Join Spring Test component lead Sam Brannen in this talk to discover what's new in Spring's testing support in 4.0 through 4.1.
This talk will provide attendees an overview of what's been deprecated, what's changed, and what's been introduced in Spring's testing support over the last two years, with real life examples and tips for best practices. Highlights include using SocketUtils to scan for free TCP & UDP server ports, the ActiveProfilesResolver API, meta-annotation support for test annotations including attribute overrides, best practices with TestNG, using Groovy scripts to configure an ApplicationContext for integration tests, improvements to SQL script execution and embedded databases, the new TestContext framework bootstrap strategy, programmatic transaction management in tests, and more.
Spring Framework 4.1 is the latest release of the popular open source application framework for Java developers with continued innovation for Java SE 8 and enterprise Java. In this presentation core Spring committer Sam Brannen will provide attendees an overview of the new enterprise features in the framework as well as new programming models and testing features.
Specifically, this talk will cover support for annotation-driven JMS listeners, JMS 2.0's shared subscriptions, JCache (JSR-107) annotations, a compiler mode for the Spring Expression Language (SpEL), flexible resolution and transformation of static web resources, and Web MVC support for Groovy markup templates.
The presentation also provides an overview of Spring 4.1's refinements in other areas, for example: Java 8's Optional type for injection points, declarative MVC view resolution, Jackson's JsonView, WebSocket scope, SockJS client support, declarative SQL scripts and programmatic transactions in the TestContext framework, integration testing with Groovy scripts, and more.
Spring has long become more than just a framework for application writing. Now there is a whole ecosystem of frameworks under Spring umbrella. This presentation is dedicated to automated testing of applications written in Spring, and more.
The respective talk was held by Kostyantyn Baranov (Senior Software Engineer, Consultant, GlobalLogic) at GlobalLogic Mykolaiv Java TechTalk #1 on July 26, 2018.
how to write functional tests with Selenium. how to set up Selenium Testing On Grails Apps In Continuous
Integration Using two approaches: The long way – using Maven and/or Ant The fast way, using the grails-
selenium-rc plug-in - ( see
http://buildchimp.com/wordpress/?p=241 )
Get the Most out of Testing with Spring 4.2Sam Brannen
Join Sam Brannen and Nicolas Fränkel to discover what's new in Spring Framework 4.2's testing support and learn tips and best practices for testing modern, Spring-based applications.
Sam Brannen is the Spring Test component lead and author of the Spring TestContext Framework, and Nicolas Fränkel is the author of the book "Integration Testing from the Trenches".
In this session, Sam and Nicolas will cover the latest testing features in Core Spring, Spring Boot, and Spring Security. In addition to new features, they will also present insider tips and best practices on integration testing with suites in TestNG, database transactions, SQL script execution, granularity of context configuration files, optimum use of the context cache, a discussion on TestNG vs. JUnit, and much more.
San Jose Selenium Meet-up PushToTest TestMaker PresentationClever Moe
With the Selenium project team's focus on making the WebDriver APIs a W3C standard, this is a good time to talk about where Selenium is going and the support it is getting from commercial open source companies. Frank Cohen, CEO at PushToTest, will discuss Selenium tools - record/playback utilities, deploying Selenium scripts to the Cloud, results analysis tools to surface functional issues and performance bottlenecks, and operational test database repositories - needed to be productive and successful with Selenium.
JUnit 5 — New Opportunities for Testing on the JVMVMware Tanzu
SpringOne Platform 2017
Sam Brannen, Switfmind
"Take a Deep Dive into JUnit 5 with core committer Sam Brannen!
Over the last decade a lot has happened in the world of Java and testing, but JUnit 4 hasn't kept up. Now JUnit 5 is here to help shape the future of testing on the JVM with a focus on Java 8 language features, extensibility, and a modern programming API for testing in Java. Moreover, JUnit isn't just a Java testing framework anymore. Third parties are already developing test engines for Scala, Groovy, Kotlin, etc. that run on the new JUnit Platform.
This session starts off with an overview of the inspiration for & architecture of JUnit 5, from launchers to test engines. Sam will then take the audience on a live coding tour, highlighting support for tagging, custom display names, dependency injection, repeated tests, parameterized tests, conditional test execution, lambda expressions for assertions, assumptions, & dynamic tests, and implementing tests via interface default methods (a.k.a., testing traits).
Next, Sam will present the new extension model in JUnit Jupiter, discussing how to author and register extensions for conditional tests, parameter resolution (a.k.a., dependency injection), lifecycle callbacks, & more.
To round off the session, Sam will quickly showcase the new JUnit Jupiter support in Spring Framework 5.0."
Selenium XPath Performance Problems in IEClever Moe
Selenium XPath Performance Problems in Microsoft Internet Explorer (MS IE). Shows why a Selenium script that runs in 3 minutes in Firefox takes 30 minutes to run in IE. And, what to do to mitigate this performance problem.
The Advanced Selenium Workshop demonstrates how organizations and test teams succeed with Selenium and Open Source Test (OST) technology and methodology as a more affordable and flexible option to the proprietary test vendors. Watch how to:
Use Selenium in Java, Python, Ruby
Data enable Selenium scripts
Selenium target locators for Ajax applications
How To Work with TinyMCE (and other Ajax components) in Selenium
Writing Selenium-based Test Object Libraries
Infinum Android Talks #17 - Testing your Android applications by Ivan KustInfinum
van will show you how to setup unit tests using Robolectric, how to test user interactions using Espresso and provide some tips and tricks for stress-free testing.
Symbiosis of test automation tools. Several tools (graphwalker/selenide/allure/sikuli/browsermob proxy) overview and practical appliance in your Selenium automation project will be presented
Arquillian (http://jboss.org/arquillian) is a test harness that simplifies integration testing using container managed resources.
ShrinkWrap (http://jboss.org/shrinkwrap) is a fluent Java API for dynamically generating deployable archives.
Real Java EE Testing with Arquillian and ShrinkWrapDan Allen
Recorded on 2010-04-30 at the Northern Virginia Software Symposium, a stop on the NFJS 2010 tour, this presentation introduces Arquillian, an extension for TestNG and JUnit that provides a component model for tests, making it simple to test real components inside a real container.
Introduction
Spring Boot testing features
Example of microservices with Spring Cloud
Component & Integration testing with Hoverfly
Contract testing with Pact or Spring Cloud Contract
Load testing with Gatling
Integration & end-to-end testing with Arquillian Cube
Summary
Developing ASP.NET Applications Using the Model View Controller Patterngoodfriday
Learn how to use the model-view-controller (MVC) pattern to take advantage of your favorite .NET Framework language for writing business logic in a way that is de-coupled from the views of the data.
Spring has long become more than just a framework for application writing. Now there is a whole ecosystem of frameworks under Spring umbrella. This presentation is dedicated to automated testing of applications written in Spring, and more.
The respective talk was held by Kostyantyn Baranov (Senior Software Engineer, Consultant, GlobalLogic) at GlobalLogic Mykolaiv Java TechTalk #1 on July 26, 2018.
how to write functional tests with Selenium. how to set up Selenium Testing On Grails Apps In Continuous
Integration Using two approaches: The long way – using Maven and/or Ant The fast way, using the grails-
selenium-rc plug-in - ( see
http://buildchimp.com/wordpress/?p=241 )
Get the Most out of Testing with Spring 4.2Sam Brannen
Join Sam Brannen and Nicolas Fränkel to discover what's new in Spring Framework 4.2's testing support and learn tips and best practices for testing modern, Spring-based applications.
Sam Brannen is the Spring Test component lead and author of the Spring TestContext Framework, and Nicolas Fränkel is the author of the book "Integration Testing from the Trenches".
In this session, Sam and Nicolas will cover the latest testing features in Core Spring, Spring Boot, and Spring Security. In addition to new features, they will also present insider tips and best practices on integration testing with suites in TestNG, database transactions, SQL script execution, granularity of context configuration files, optimum use of the context cache, a discussion on TestNG vs. JUnit, and much more.
San Jose Selenium Meet-up PushToTest TestMaker PresentationClever Moe
With the Selenium project team's focus on making the WebDriver APIs a W3C standard, this is a good time to talk about where Selenium is going and the support it is getting from commercial open source companies. Frank Cohen, CEO at PushToTest, will discuss Selenium tools - record/playback utilities, deploying Selenium scripts to the Cloud, results analysis tools to surface functional issues and performance bottlenecks, and operational test database repositories - needed to be productive and successful with Selenium.
JUnit 5 — New Opportunities for Testing on the JVMVMware Tanzu
SpringOne Platform 2017
Sam Brannen, Switfmind
"Take a Deep Dive into JUnit 5 with core committer Sam Brannen!
Over the last decade a lot has happened in the world of Java and testing, but JUnit 4 hasn't kept up. Now JUnit 5 is here to help shape the future of testing on the JVM with a focus on Java 8 language features, extensibility, and a modern programming API for testing in Java. Moreover, JUnit isn't just a Java testing framework anymore. Third parties are already developing test engines for Scala, Groovy, Kotlin, etc. that run on the new JUnit Platform.
This session starts off with an overview of the inspiration for & architecture of JUnit 5, from launchers to test engines. Sam will then take the audience on a live coding tour, highlighting support for tagging, custom display names, dependency injection, repeated tests, parameterized tests, conditional test execution, lambda expressions for assertions, assumptions, & dynamic tests, and implementing tests via interface default methods (a.k.a., testing traits).
Next, Sam will present the new extension model in JUnit Jupiter, discussing how to author and register extensions for conditional tests, parameter resolution (a.k.a., dependency injection), lifecycle callbacks, & more.
To round off the session, Sam will quickly showcase the new JUnit Jupiter support in Spring Framework 5.0."
Selenium XPath Performance Problems in IEClever Moe
Selenium XPath Performance Problems in Microsoft Internet Explorer (MS IE). Shows why a Selenium script that runs in 3 minutes in Firefox takes 30 minutes to run in IE. And, what to do to mitigate this performance problem.
The Advanced Selenium Workshop demonstrates how organizations and test teams succeed with Selenium and Open Source Test (OST) technology and methodology as a more affordable and flexible option to the proprietary test vendors. Watch how to:
Use Selenium in Java, Python, Ruby
Data enable Selenium scripts
Selenium target locators for Ajax applications
How To Work with TinyMCE (and other Ajax components) in Selenium
Writing Selenium-based Test Object Libraries
Infinum Android Talks #17 - Testing your Android applications by Ivan KustInfinum
van will show you how to setup unit tests using Robolectric, how to test user interactions using Espresso and provide some tips and tricks for stress-free testing.
Symbiosis of test automation tools. Several tools (graphwalker/selenide/allure/sikuli/browsermob proxy) overview and practical appliance in your Selenium automation project will be presented
Arquillian (http://jboss.org/arquillian) is a test harness that simplifies integration testing using container managed resources.
ShrinkWrap (http://jboss.org/shrinkwrap) is a fluent Java API for dynamically generating deployable archives.
Real Java EE Testing with Arquillian and ShrinkWrapDan Allen
Recorded on 2010-04-30 at the Northern Virginia Software Symposium, a stop on the NFJS 2010 tour, this presentation introduces Arquillian, an extension for TestNG and JUnit that provides a component model for tests, making it simple to test real components inside a real container.
Introduction
Spring Boot testing features
Example of microservices with Spring Cloud
Component & Integration testing with Hoverfly
Contract testing with Pact or Spring Cloud Contract
Load testing with Gatling
Integration & end-to-end testing with Arquillian Cube
Summary
Developing ASP.NET Applications Using the Model View Controller Patterngoodfriday
Learn how to use the model-view-controller (MVC) pattern to take advantage of your favorite .NET Framework language for writing business logic in a way that is de-coupled from the views of the data.
WPF and Prism 4.1 Workshop at BASTA AustriaRainer Stropek
At BASTA Austria (http://www.basta-austria.at) I did a workshop about WPF and Prism. This is my slide deck. It summarizes the most important take-aways from the workshop. Additionally it contains sample code snippets.
A brief introduction to javascript test driven development (TDD) towards several point of views by using qUnit, Karma & Jasmine, NodeJS tape module and custom frameworks.
Mastering Mock Objects - Advanced Unit Testing for JavaDenilson Nastacio
A high-level description of mock testing techniques and their implementation for the Java programming language.
This presentation specifically focus on the JMockit and JMock frameworks.
Integration testing is hard, and often teams are tempted to do it in production. Testcontainers allows writing meaningful integration tests spawning Docker containers for databases, queue systems, kv-store, other services. The talk, a blend of slides and live code, will show how we are able to deploy without fear while integrating with a dozen of different datastores. Don't mock your database with fake data anymore, work with real data
Here is update version of past talk about Robolectric tests and around.
The text for talks is here:
https://docs.google.com/document/d/1GhgkxOdkKbbYrBKsNoCiATuI-2GXO78ElVP0A06Cv-k/edit?usp=sharing
Shazam is a very popular audio recognition app. It is installed on 100M+ Android devices and it’s growing rapidly. In this talk, we will address how we made the release schedule faster, more predictable and with more features by using BDD and automation testing.
We’ll demonstrate how that can be done without slowing down or hindering the development process and why our developers actually find writing tests is fun. Finally, we’ll look at how our testing strategy has translated to our testing framework and hardware infrastructure.
Today's applications don't live in a vacuum - you need to take the applications to where your users are. Let Spring's REST support along with its powerful client-side technology support, help you get there faster.
Unit Testing in JavaScript with MVC and QUnitLars Thorup
While more and more application code move from the back-end to a JavaScript-based front-end, we still need to test this code efficiently. Testing JavaScript is often done using browser automation frameworks, but system-level testing is slow and brittle.
Here we present a way to structure your JavaScript application according to the Model-View-Controller (MVC) design pattern and how this enables us to write unit tests for a large part of the application logic, using a testing framework like QUnit.
Sample source code available at http://www.zealake.com/public/javascript-unit-testing.zip
One of the best features of ASP.NET MVC is that it's totally extensible: if you don't like the way the framework works or if you have scenarios not covered by it, you can change the behaviors by extending the defaults or by writing your owns.
In this presentation I'll go through all the main extensibility points and explain how to leverage the main ones
Similar to Testing Web Apps with Spring Framework (20)
Italy Agriculture Equipment Market Outlook to 2027harveenkaur52
Agriculture and Animal Care
Ken Research has an expertise in Agriculture and Animal Care sector and offer vast collection of information related to all major aspects such as Agriculture equipment, Crop Protection, Seed, Agriculture Chemical, Fertilizers, Protected Cultivators, Palm Oil, Hybrid Seed, Animal Feed additives and many more.
Our continuous study and findings in agriculture sector provide better insights to companies dealing with related product and services, government and agriculture associations, researchers and students to well understand the present and expected scenario.
Our Animal care category provides solutions on Animal Healthcare and related products and services, including, animal feed additives, vaccination
Gen Z and the marketplaces - let's translate their needsLaura Szabó
The product workshop focused on exploring the requirements of Generation Z in relation to marketplace dynamics. We delved into their specific needs, examined the specifics in their shopping preferences, and analyzed their preferred methods for accessing information and making purchases within a marketplace. Through the study of real-life cases , we tried to gain valuable insights into enhancing the marketplace experience for Generation Z.
The workshop was held on the DMA Conference in Vienna June 2024.
1.Wireless Communication System_Wireless communication is a broad term that i...JeyaPerumal1
Wireless communication involves the transmission of information over a distance without the help of wires, cables or any other forms of electrical conductors.
Wireless communication is a broad term that incorporates all procedures and forms of connecting and communicating between two or more devices using a wireless signal through wireless communication technologies and devices.
Features of Wireless Communication
The evolution of wireless technology has brought many advancements with its effective features.
The transmitted distance can be anywhere between a few meters (for example, a television's remote control) and thousands of kilometers (for example, radio communication).
Wireless communication can be used for cellular telephony, wireless access to the internet, wireless home networking, and so on.
Bridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptxBrad Spiegel Macon GA
Brad Spiegel Macon GA’s journey exemplifies the profound impact that one individual can have on their community. Through his unwavering dedication to digital inclusion, he’s not only bridging the gap in Macon but also setting an example for others to follow.
Instagram has become one of the most popular social media platforms, allowing people to share photos, videos, and stories with their followers. Sometimes, though, you might want to view someone's story without them knowing.
2.Cellular Networks_The final stage of connectivity is achieved by segmenting...JeyaPerumal1
A cellular network, frequently referred to as a mobile network, is a type of communication system that enables wireless communication between mobile devices. The final stage of connectivity is achieved by segmenting the comprehensive service area into several compact zones, each called a cell.
Meet up Milano 14 _ Axpo Italia_ Migration from Mule3 (On-prem) to.pdfFlorence Consulting
Quattordicesimo Meetup di Milano, tenutosi a Milano il 23 Maggio 2024 dalle ore 17:00 alle ore 18:30 in presenza e da remoto.
Abbiamo parlato di come Axpo Italia S.p.A. ha ridotto il technical debt migrando le proprie APIs da Mule 3.9 a Mule 4.4 passando anche da on-premises a CloudHub 1.0.
4. - Build web applications with Spring Web MVC
- Familiar with mock objects unit testing (JUnit and Mockito)
4
Assumptions on Audience
5. Spring Controllers Testing
- Example Domain Model
- Subject Under Test
- Pure Unit Tests
Spring MVC Test Framework
- Standalone Server-Side Integration Tests
- Web Application Context Server-Side Integration Tests
Further materials
Q&A
5
Agenda
17. ChannelController behaviour
- Positive test case
When we are looking for an existent channel by its id
- Negative test case
When we are looking for an absent channel by its id
17
What we are going to test
22. 22
Unit Test Scaffolding
!
public class ChannelControllerTest {
@Mock
private ChannelRepository channelRepository;
!
@InjectMocks
private ChannelController channelController =
// optional new ChannelController();
}
24. 24
Unit Test Scaffolding
@RunWith(MockitoJUnitRunner.class)
public class ChannelControllerTest {
@Mock
private ChannelRepository channelRepository;
!
@InjectMocks
private ChannelController channelController =
// optional new ChannelController();
!
!
@Mock
private Channel channel; // dummy
// test cases go here
}
26. 26
Positive Test Case
@Test
public void itShouldFindChannel() {
when(channelRepository.findOne(1))
.thenReturn(channel);
!
assertThat(
channelController.getChannel(1), is(channel)
);
}
27. 27
Negative Test Case
@Test
public void itShouldNotFoundChannel() {
// optional
when(channelRepository.findOne(-1))
.thenReturn(null);
}
28. 28
Negative Test Case
@Test(expected = ChannelNotFoundException.class)
public void itShouldNotFoundChannel() {
// optional
when(channelRepository.findOne(-1))
.thenReturn(null);
!
channelController.getChannel(-1);
}
29. - Easy to write
- Incredibly fast (a few milliseconds per test case)
29
Pros
30. - Can use Spring mocks from org.springframework.mock.web
- MockHttpServletRequest/Response/Session
- MockMultipartFile
- MockFilterChain
…
- ModelAndViewAssert from org.springframework.test.web
to apply asserts on a resulting ModelAndView
30
Additional Capabilities on Demand
31. - A lot left untested
- Request mappings
- Type conversion
- Transactions
- Data binding
- Validation
- Filters
- …
- No Spring annotations used
- No DispatcherServlet interactions
- No actual Spring MVC configuration loaded
31
Caveats
36. - Response status, headers, content
- Spring MVC and Servlet specific results
- Model, flash, session, request attributes
- Mapped controller method
- Resolved exceptions
- Various options for asserting the response body
- JsonPath, XPath, XMLUnit
36
What can be tested
37. - Almost all template technologies are supported
- JSON, XML, Velocity, Freemarker, Thymeleaf, PDF etc.
- Except JSP (because it relies on Servlet Container)
- you can assert only on the selected JSP view name
- No actual redirecting or forwarding
- you can assert the redirected or forwarded URL
37
Testing View Layer
38. Standalone setup for testing one individual controller at a time
without actual Spring MVC configuration loading
38
MockMvc “Standalone” Setup
private ChannelController controller = //...
!
private MockMvc mockMvc;
!
public void setUp() {
mockMvc = MockMvcBuilders.standaloneSetup(controller)
.build();
}
44. - MockMvcBuilders.* to set up MockMvc instances
- MockMvcRequestBuilders.* to create requests
- MockMvcResultMatchers.* for request result assertions on
44
Useful Static Imports
61. ChannelController instantiated
Mock of ChannelRepository injected
MockMvc was set-upped
MockHttpServletRequest prepared
Executed via DispatcherServlet
Assertions applied on the resulting MockHttpServletResponse
Assertions applied on the resulting MvcResult
61
What happened
62. - Easy to write
- Uses Spring annotations
- Always interacts with DispatcherServlet
62
Pros
63. - A bit slow (about 1 second for the first test case)
- No Actual Spring MVC configuration loaded
63
Caveats
75. Actual Web MVC application context loaded
MockHttpServletRequest prepared
Executed via DispatcherServlet
Assertions applied on the resulting MockHttpServletResponse
Assertions applied on the resulting MvcResult
75
What happened
76. - Easy to write
- Loads actual Spring MVC configuration (cacheable)
- Uses Spring annotations
- Always Interacts with DispatcherServlet
76
Pros
77. - Slower than the “Standalone” option (depends on amount of beans
in a particular Spring Mvc configuration)
- Does not replace end-to-end testing like Selenium
77
Caveats
79. Integration between Spring MVC Test Framework and HtmlUnit.
Repository: https://github.com/spring-projects/spring-test-htmlunit
Documentation: https://github.com/spring-projects/spring-test-
htmlunit/blob/master/src/asciidoc/index.adoc
79
Spring MVC Test HtmlUnit
81. Webinar: Testing Web Applications with Spring 3.2
by Sam Brannen (Swiftmind) and Rossen Stoyanchev
https://www.youtube.com/watch?v=K6x8LE7Qd1Q
Spring Testing
by Mattias Severson
https://www.youtube.com/watch?v=LYVJ69h76nw
!
81
Videos