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
230
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
It Takes Two to Tango – Designing Module Interactions in Modulithic Spring Applications
olivergierke
5
580
Bottom-Up Architecture – Bridging the Achitecture Code Gap
olivergierke
4
830
Spring Modulith – A Deep Dive
olivergierke
7
4.1k
Spring for the Architecturally Curious Developer
olivergierke
5
1.8k
Spring Boot 3 & Spring Framework 6
olivergierke
4
2k
Architecturally-evident Java Applications with jMolecules
olivergierke
8
2.8k
A Deep Dive into Spring Application Events
olivergierke
12
3.2k
Building Better Monoliths – Modulithic Applications with Spring Boot
olivergierke
4
910
Spring HATEOAS – Hypermedia APIs with Spring
olivergierke
1
690
Other Decks in Programming
See All in Programming
ASP. NET CoreにおけるWebAPIの最新情報
tomokusaba
0
360
Immutable ActiveRecord
megane42
0
130
ARA Ansible for the teams
kksat
0
150
なぜイベント駆動が必要なのか - CQRS/ESで解く複雑系システムの課題 -
j5ik2o
7
2.5k
Unity Android XR入門
sakutama_11
0
140
CI改善もDatadogとともに
taumu
0
110
『品質』という言葉が嫌いな理由
korimu
0
160
Honoとフロントエンドの 型安全性について
yodaka
4
250
『GO』アプリ バックエンドサーバのコスト削減
mot_techtalk
0
130
【PHP】破壊的バージョンアップと戦った話〜決断と説得
satoshi256kbyte
0
120
自分ひとりから始められる生産性向上の取り組み #でぃーぷらすオオサカ
irof
8
2.6k
バックエンドのためのアプリ内課金入門 (サブスク編)
qnighy
8
1.7k
Featured
See All Featured
Build your cross-platform service in a week with App Engine
jlugia
229
18k
[RailsConf 2023 Opening Keynote] The Magic of Rails
eileencodes
28
9.3k
Keith and Marios Guide to Fast Websites
keithpitt
411
22k
Practical Tips for Bootstrapping Information Extraction Pipelines
honnibal
PRO
12
950
Music & Morning Musume
bryan
46
6.3k
Fontdeck: Realign not Redesign
paulrobertlloyd
82
5.4k
Dealing with People You Can't Stand - Big Design 2015
cassininazir
366
25k
Site-Speed That Sticks
csswizardry
3
370
GraphQLとの向き合い方2022年版
quramy
44
13k
Writing Fast Ruby
sferik
628
61k
Six Lessons from altMBA
skipperchong
27
3.6k
Imperfection Machines: The Place of Print at Facebook
scottboms
267
13k
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