Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
Spring MVC Integration Testing
Search
Oliver Drotbohm
August 15, 2013
Programming
260
2
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
Spring MVC Integration Testing
Slide of my talk at JUG Ostfalen about Spring MVC integration testing
Oliver Drotbohm
August 15, 2013
More Decks by Oliver Drotbohm
See All by Oliver Drotbohm
What's new in Spring Modulith?
olivergierke
1
320
Domain-centric? Why Hexagonal and Onion Architecture Are Answers to the Wrong Question
olivergierke
4
2.1k
It Takes Two to Tango – Designing Module Interactions in Modulithic Spring Applications
olivergierke
5
830
Bottom-Up Architecture – Bridging the Achitecture Code Gap
olivergierke
4
1.1k
Spring Modulith – A Deep Dive
olivergierke
9
5.6k
Spring for the Architecturally Curious Developer
olivergierke
5
1.9k
Spring Boot 3 & Spring Framework 6
olivergierke
4
2.1k
Architecturally-evident Java Applications with jMolecules
olivergierke
9
3.2k
A Deep Dive into Spring Application Events
olivergierke
12
3.5k
Other Decks in Programming
See All in Programming
「AIで開発し、AIを届ける」をEvalでつなぐ 〜AIネイティブに始めるプロダクト開発の実践〜 / Connecting "Develop with AI, deliver AI" with Eval
rkaga
4
5.1k
Lemonade + Foundry Toolkit でお手軽アプリ開発
seosoft
1
340
コンテキストの使い捨てをやめる — ビジネスルール駆動開発と miko —
ioki
0
210
Snowflake Summitでの新機能 CoCo / CoWork / snowflake-summit-2026-overall-what-new-coco
tatsuhiro
1
140
The ROI of Quarkus for Spring Boot Applications
hollycummins
0
120
3Dシーンの圧縮
fadis
1
770
Agentic UI
manfredsteyer
PRO
0
160
Lessons from Spec-Driven Development
simas
PRO
0
200
「エンジニアインターン、どうやって取った?」準備のリアルを語るLT会 Progate BAR
akiomatic
0
130
ユニットテストの先へ:テスト技法で要求・仕様を整理するJava開発実践 / Beyond_Unit_Testing_Practical_Java_Development_Techniques_for_Organizing_Requirements_and_Specifications
shimashima35
0
410
肥大化するレガシーコードに立ち向かうためのインターフェース分離と依存の逆転 / JJUG CCC 2026 Spring
hirokunimaeta
0
560
Mujeres en SEO Summit 2026 - Greatest Disaster Hits en Web Performance
guaca
0
180
Featured
See All Featured
Ruling the World: When Life Gets Gamed
codingconduct
0
250
Unlocking the hidden potential of vector embeddings in international SEO
frankvandijk
0
840
How To Speak Unicorn (iThemes Webinar)
marktimemedia
1
490
We Have a Design System, Now What?
morganepeng
55
8.2k
How to Create Impact in a Changing Tech Landscape [PerfNow 2023]
tammyeverts
55
3.4k
Digital Projects Gone Horribly Wrong (And the UX Pros Who Still Save the Day) - Dean Schuster
uxyall
1
1.7k
How to audit for AI Accessibility on your Front & Back End
davetheseo
0
430
Navigating Weather and Climate Data
rabernat
0
220
The untapped power of vector embeddings
frankvandijk
2
1.8k
WENDY [Excerpt]
tessaabrams
11
38k
Lightning Talk: Beautiful Slides for Beginners
inesmontani
PRO
2
580
Let's Do A Bunch of Simple Stuff to Make Websites Faster
chriscoyier
508
140k
Transcript
Spring MVC Integration Testing Oliver Gierke
Oliver Gierke Spring Data Core/JPA/MongoDB JPA 2.1 Expert Group
[email protected]
www.olivergierke.de olivergierke
We want to build quality software!
We want to build quality software!
Testable software is quality software!
Testable software is quality software!
Only testable software can be changed easily.
Only testable software can be changed easily.
Testing should cause as little overhead as possible.
Testing should cause as little overhead as possible.
Unit testing VS. Integration testing
Side track: Spring MVC
Spring MVC Infrastructure HTTP / Servlet API Controller implementations Application
services
Spring MVC Infrastructure HTTP / Servlet API Controller implementations Application
services
Spring MVC Infrastructure HTTP / Servlet API Controller implementations Application
services
@Controller class PersonController { @RequestMapping(value = "/people", method = GET)
HttpEntity<List<Person>> showPeople() { List<Person> result = people.findAll(); return new ResponseEntity<>(result, HttpStatus.OK); } @RequestMapping(value = "/people", method = POST) HttpEntity<Void> create(@RequestBody Person person) { Person result = people.create(person); HttpHeaders = new HttpHeaders(); headers.setLocation(…); return new ResponseEntity<>(headers, HttpStatus.CREATED); } } REST
@Controller class PersonController { @RequestMapping(value = "/people", method = GET)
String showPeople(Model model) { model.put("people", people.findAll()); return "people"; } @RequestMapping(value = "/people", method = POST) String create(@ModelAttribute Person person, Model model) { Person result = people.create(person); // Add success or error message to model return "people"; } } View resolution
Unit testable Mock dependencies Call methods Verify outcome
What about the web layer overall?
Left untested Servlet API setup Spring MVC setup Request mapping
Custom extensions
Spring MVC HTTP / Servlet API Controller implementations Application services
Extensions
The 2 runtimes approach
Test process Use embedded container Bootstrap before tests Execute tests
Shutdown after tests
Application in embedded Jetty / Tomcat Test execution JVM JVM
Application in embedded Jetty / Tomcat Test execution JVM JVM
Environment implications Separate process Port required in environment Build setup
tweaks
Testing implications Data setup Transaction management
Works, but has its issues.
The integrated runtime approach
Test Context Framework Bootstraps ApplicationContexts Transaction management Context caching Extensible
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:application-context.xml") @Transactional public class SampleIntegrationTests { @Autowired Dependency dependency;
@Test public void myTest() { // Implement test here } } Sample test case
Test Context Framework ApplicationContext
Test Context Framework ApplicationContext MockMVC
Mock MVC Integrates with Test Framework API to build "requests"
API to define result expectations
@RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration("classpath:application-context.xml") public class SampleIntegrationTests { @Autowired WebApplicationContext context;
MockMvc mvc; @Before public void setUp() { this.mvc = MockMvcBuilders. webAppContextSetup(this.context).build(); } } MVC testing
import static org.sfw.….MockMvcRequestBuilders.*; import static org.sfw.….MockMvcResultMatchers.*; public class SampleIntegrationTests {
@Test public void setUp() { this.mvc.perform(get("/accounts/1") .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().contentType("application/json")) .andExpect(jsonPath("$.name").value("Lee")); } } MVC testing
Setup Bootstrap from WebApplicationContext Register Servlet API artifacts Support for
individual controllers
Building requests Execute HTTP methods Define request parameters / payload
HTTP headers
Define expectations Response status, header, body XPath / JSONPath
DEMO
Recap
In-container MVC testing
Benefits No infrastructure implications No build tweaks necessary Standard test
transaction handling Context caching
Client side REST tests
import static org.sfw.….MockRestResponseCreators.*; RestTemplate restTemplate = new RestTemplate(); MockRestServiceServer mockServer
= MockRestServiceServer.createServer(restTemplate); mockServer.expect(requestTo("/greeting")) .andRespond(withSuccess("Hello world!", "text/plain")); // use RestTemplate mockServer.verify(); Mock REST server
Questions?
Resources Reference documentation Spring RESTBucks