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
2
220
Spring MVC Integration Testing
Slide of my talk at JUG Ostfalen about Spring MVC integration testing
Oliver Drotbohm
August 15, 2013
Tweet
Share
More Decks by Oliver Drotbohm
See All by Oliver Drotbohm
Spring Modulith – A Deep Dive
olivergierke
7
1.8k
Spring for the Architecturally Curious Developer
olivergierke
5
1.6k
Spring Boot 3 & Spring Framework 6
olivergierke
4
1.8k
Architecturally-evident Java Applications with jMolecules
olivergierke
8
2.4k
A Deep Dive into Spring Application Events
olivergierke
12
2.9k
Building Better Monoliths – Modulithic Applications with Spring Boot
olivergierke
4
820
Spring HATEOAS – Hypermedia APIs with Spring
olivergierke
1
560
Building Better Monoliths – Modulithic Applications with Spring Boot
olivergierke
6
3.8k
REST Beyond the Obvious – API Design for Ever Evolving Systems
olivergierke
5
1.1k
Other Decks in Programming
See All in Programming
今、知っておきたい! 生成AIエージェントの世界
elith
3
350
FigmaとPHPで作る1ミリたりとも表示崩れしない最強の帳票印刷ソリューション
ttskch
43
19k
Rubyでたのしむクリエイティブコーディング/Enjoy Creative coding with Ruby
chobishiba
1
180
Zero Waste, Radical Magic, and Italian Graft – Quarkus Efficiency Secrets
hollycummins
0
230
[技育CAMPアカデミア]アイディアを形に!【超入門】スマホアプリ開発〜リリースまでの流れをご紹介
teamlab
PRO
0
370
Node.js v22 で変わること
yosuke_furukawa
PRO
9
3.2k
Build Apps for iOS, Android & Desktop in 100% Kotlin With Compose Multiplatform (mDevCamp 2024)
zsmb
0
320
try! Swift Tokyo 2024 参加報告 / try! Swift Tokyo 2024 Report
hironytic
0
200
はてなにおける CSS Modules、及び CSS Modules に足りないもの / CSS Modules in Hatena, and CSS Modules missing parts
mizdra
7
920
Code Reviews
bkuhlmann
4
890
スキーマ駆動開発による品質とスピードの両立 - 私達は何故、スキーマを書くのか
kentaroutakeda
0
170
PHP8.3の機能を振り返る / Review of PHP 8.3 features
seike460
PRO
1
110
Featured
See All Featured
[Rails World 2023 - Day 1 Closing Keynote] - The Magic of Rails
eileencodes
2
1.3k
How to Ace a Technical Interview
jacobian
272
22k
The Invisible Side of Design
smashingmag
294
49k
Why You Should Never Use an ORM
jnunemaker
PRO
51
8.6k
YesSQL, Process and Tooling at Scale
rocio
164
13k
Reflections from 52 weeks, 52 projects
jeffersonlam
345
19k
KATA
mclloyd
15
12k
How to train your dragon (web standard)
notwaldorf
73
5.2k
Thoughts on Productivity
jonyablonski
58
3.8k
The Mythical Team-Month
searls
216
42k
Scaling GitHub
holman
457
140k
"I'm Feeling Lucky" - Building Great Search Experiences for Today's Users (#IAC19)
danielanewman
221
21k
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