SlideShare a Scribd company logo
Spring Testing
Mattias Severson
Mattias
@mattiasseverson
!
https://github.com/matsev/spring-testing
Agenda
• Basic Spring Testing
• Embedded Database
• Transactions
• Profiles
• Controller Tests
• Spring Boot
Bank App
Architecture
AccountService
BankController
ImmutableAccount
AccountEntityAccountRepository
Basics
!
!
public class AccountServiceTest {
!
@Autowired
AccountService aService;
!
@Test
public void testDoSomething() {
aService.doSomething();
// verify ...
}
}
@Autowired
@ContextConfiguration
!
@ContextConfiguration("classes=AppConfig.class")
public class AccountServiceTest {
!
@Autowired
AccountService aService;
!
@Test
public void testDoSomething() {
aService.doSomething();
// verify ...
}
}
!
!
public class AccountServiceTest {
!
@Autowired
AccountService aService;
!
@Test
public void testDoSomething() {
aService.doSomething();
// verify ...
}
}
SpringJUnit4ClassRunner
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(“classes=TestConfig.class")
public class AccountServiceTest {
!
@Autowired
AccountService aService;
!
@Test
public void testDoSomething() {
aService.doSomething();
// verify ...
}
}
!
@ContextConfiguration("classes=TestConfig.class
public class AccountServiceTest {
!
@Autowired
AccountService aService;
!
@Test
public void testDoSomething() {
aService.doSomething();
// verify ...
}
}
Embedded DB
AccountRepository AccountEntity
Java Config
@Configuration
public class EmbeddedDbConfig {
!
@Bean(destroyMethod = "shutdown")
public EmbeddedDatabase dataSource() {
return new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.HSQL)
.addScript(“classpath:db-schema.sql”)
.addScript(“classpath:db-test-data.sql”)
.build();
}
}
XML Config
<jdbc:embedded-database id="dataSource" type="HSQL">
<jdbc:script location="classpath:db-schema.sql"/>
<jdbc:script location="classpath:db-test-data.sql"/>
</jdbc:embedded-database>
Demo
Transactions
Tx Test
!
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/application-context.xml")
public class AccountServiceTest {
!
@Test
public void testDoSomething() {
// call DB
}
!
}
@Transactional
!
!
!
!
@Test
public void testDoSomething() {
// call DB
}
!
Avoid False Positives
Always flush() before validation!
!
• Hibernate!
- sessionFactory.getCurrentSession().flush();!
!
• JPA!
- entityManager.flush();
Demo
No Transactions?
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("...")
public class AccountRepositoryTest {
!
@Autowired
AccountRepository accountRepo;
!
@Before
public void setUp() {
accountRepo.deleteAll();
accountRepo.save(testData);
}
}
Spring Profiles
Java Config Profile
!
@Configuration
public class EmbeddedDbConfig {
!
@Bean
public DataSource dataSource() {
return new EmbeddedDatabaseBuilder().
// ...
}
}
@Profile(“testProfile”)
Component Profile
!
@Component
public class SomeClass implements SomeInterface {
!
}
@Profile(“testProfile”)
XML Profiles
<beans ...>
!
!
<bean id="dataSource">
<!-- Test data source -->
</bean>
!
!
!
<bean id="dataSource">
<!-- Production data source -->
</bean>
!
!
</beans>
!
!
<beans profile="testProfile">
!
!
!
</beans>
!
<beans profile="prodProfile">
!
!
!
</beans>
!
Tests and Profiles
!
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(“/application-context.xml”)
public class SomeTest {
!
@Autowired
SomeClass someClass;
!
@Test
public void testSomething() { ... }
}
@ActiveProfiles("testProfile")
Demo
AccountRepository AccountEntity
AccountService ImmutableAccount
web.xml
<web-app ...>
!
!
!
!
!
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
!
</web-app>
!
!
<context-param>
<param-name>spring.profiles.active</param-name>
<param-value>someProfile</param-value>
</context-param>
ApplicationContext
AnnotationConfigApplicationContext ctx =
new AnnotationConfigApplicationContext();
ctx.getEnvironment().setActiveProfiles("someProfile");
ctx.register(SomeConfig.class);
ctx.scan("com.jayway.demo");
ctx.refresh();
Env Property
System.getProperty(“spring.profiles.active”);
mvn -Dspring.profiles.active=testProfile
Default Profiles
ctx.getEnvironment().setDefaultProfiles("...");
System.getProperty("spring.profiles.default");
<context-param>
<param-name>spring.profiles.default</param-name>
<param-value>defaultProfile</param-value>
</context-param>
<beans profile="default">
<!-- default beans -->
</beans>

@Profile("default")

Profile Alternatives
• .properties
• Maven Profile
Test Controller
AccountRepository
AccountService
AccountEntity
ImmutableAccount
BankController
Spring MVC Test Framework
• Call Controllers through DispatcherServlet
• MockHttpServletRequest
• MockHttpServletResponse
MockMvc
MockMvc mockMvc = MockMvcBuilders
.standaloneSetup(new BankController())
.build();
MockMvc mockMvc = MockMvcBuilders
.standaloneSetup(new BankController())
.setMessageConverters(...)
.setValidator(...)
.setConversionService(...)
.addInterceptors(...)
.setViewResolvers(...)
.setLocaleResolver(...)
.addFilter(...)
.build();
MockMvc
MockMvc mockMvc = MockMvcBuilders
.build();
MockMvc mockMvc = MockMvcBuilders
.standaloneSetup(new BankController())
.setMessageConverters(...)
.setValidator(...)
.setConversionService(...)
.addInterceptors(...)
.setViewResolvers(...)
.setLocaleResolver(...)
.addFilter(...)
.build();
Assertions
mockMvc.perform(get("/url")
.accept(MediaType.APPLICATION_XML))
.andExpect(response().status().isOk())
.andExpect(content().contentType(“MediaType.APPLICATION_XML”))
.andExpect(xpath(“key”).string(“value”))
.andExpect(redirectedUrl(“url”))
.andExpect(model().attribute(“name”, value));
@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/application-context.xml")
@WebAppConfiguration
public class WebApplicationTest {
!
@Autowired
WebApplicationContext wac;
!
@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/application-context.xml")
@WebAppConfiguration
public class WebApplicationTest {
!
@Autowired
WebApplicationContext wac;
!
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/application-context.xml")
@WebAppConfiguration
public class WebApplicationTest {
!
@Autowired
WebApplicationContext wac;
!
MockMvc mockMvc;
!
@Before
public void setUp() {
MockMvcBuilders.
.webAppContextSetup(wac)
.build();
}
Demo
Testing Views
• Supported templates
- JSON!
- XML!
- Velocity!
- Thymeleaf!
• Except JSP
Spring Boot
test
Spring Boot Integration Test
appCtx
DB
dataSrctxMngr
Embedded App Server
HTTP
Spring Boot Integration Tests
@SpringApplicationConfiguration
@IntegrationTest
Test RESTful API
• RestTemplate
• Selenium
• HttpClient
• ...
REST Assured
@Test
public void shouldGetSingleAccount() {
expect().
statusCode(HttpStatus.SC_OK).
contentType(ContentType.JSON).
body("accountNumber", is(1)).
body("balance", is(100)).
when().
get("/account/1");
}
Demo
Conclusions
• Basic Spring Testing!
• Embedded Database!
• Transactions!
• Profiles!
• Controller Tests!
• Spring Boot
Questions?
@mattiasseverson
!
https://github.com/matsev/spring-testing

More Related Content

PPTX
Api testing
PDF
Automated Testing in Angular Slides
PPTX
CrossUI Tutorial - Advanced - CRUD
PDF
Service objects in Rails tests - factory_girl replacement
PDF
Testing and Software Writer a year later
PDF
Why vREST?
PDF
Automate REST API Testing
PPTX
Sync Workitems between multiple Team Projects #vssatpn
Api testing
Automated Testing in Angular Slides
CrossUI Tutorial - Advanced - CRUD
Service objects in Rails tests - factory_girl replacement
Testing and Software Writer a year later
Why vREST?
Automate REST API Testing
Sync Workitems between multiple Team Projects #vssatpn

What's hot (17)

PDF
Accelerating DevOps Collaboration with Sauce Labs and JIRA
PDF
Client side unit tests - using jasmine & karma
PDF
How to tdd your mvp
PDF
Modern Tools for API Testing, Debugging and Monitoring
PPTX
Api Testing
PPTX
Test api
PDF
Combining Front-End and Backend Testing with Sauce Labs & BlazeMeter
PDF
HTBYOOFIYRHT RubyConf
PDF
Web Performance Culture and Tools at Etsy
PPTX
Database DevOps Anti-patterns
PDF
Reasons To Automate API Testing Process
PPTX
DevOps 101 for data professionals
PPTX
Web API testing : A quick glance
PPTX
Getting CI right for SQL Server
PPTX
Test first
PPTX
B4USolution_API-Testing
PPTX
Api Testing
Accelerating DevOps Collaboration with Sauce Labs and JIRA
Client side unit tests - using jasmine & karma
How to tdd your mvp
Modern Tools for API Testing, Debugging and Monitoring
Api Testing
Test api
Combining Front-End and Backend Testing with Sauce Labs & BlazeMeter
HTBYOOFIYRHT RubyConf
Web Performance Culture and Tools at Etsy
Database DevOps Anti-patterns
Reasons To Automate API Testing Process
DevOps 101 for data professionals
Web API testing : A quick glance
Getting CI right for SQL Server
Test first
B4USolution_API-Testing
Api Testing
Ad

Viewers also liked (20)

PDF
ConFESS 2013 - Comparing Functional Java Frameworks
PDF
jDays 2015 - Getting Familiar with Spring Boot
PDF
SpringOne 2GX 2013 - Spring Testing
PDF
GeeCON 2014 - Functional Programming without Lambdas
PDF
Software Passion Summit 2012 - Testing of Spring
PDF
Spring santosh
PDF
Spring complete notes natraz
PDF
Spring Boot
PDF
Hibernate natraz
PDF
Spring Booted, But... @JCConf 16', Taiwan
PDF
AppSec & Microservices - Velocity 2016
PDF
Spring Boot
PDF
Get Hip with JHipster: Spring Boot + AngularJS + Bootstrap - DOSUG February 2016
PDF
Microservices vs monolithic
PDF
Microservices for the Masses with Spring Boot, JHipster, and JWT - Rich Web 2016
PPT
Seminar on Project Management by Rj
PDF
Principles of microservices velocity
PPTX
Weblogic application server
PDF
Getting Started with Angular - Stormpath Webinar, January 2017
ConFESS 2013 - Comparing Functional Java Frameworks
jDays 2015 - Getting Familiar with Spring Boot
SpringOne 2GX 2013 - Spring Testing
GeeCON 2014 - Functional Programming without Lambdas
Software Passion Summit 2012 - Testing of Spring
Spring santosh
Spring complete notes natraz
Spring Boot
Hibernate natraz
Spring Booted, But... @JCConf 16', Taiwan
AppSec & Microservices - Velocity 2016
Spring Boot
Get Hip with JHipster: Spring Boot + AngularJS + Bootstrap - DOSUG February 2016
Microservices vs monolithic
Microservices for the Masses with Spring Boot, JHipster, and JWT - Rich Web 2016
Seminar on Project Management by Rj
Principles of microservices velocity
Weblogic application server
Getting Started with Angular - Stormpath Webinar, January 2017
Ad

Similar to GeeCON 2014 - Spring Testing (20)

PDF
Serverless Apps with AWS Step Functions
PDF
Continuous Delivery: How RightScale Releases Weekly
PPT
Netserv Software Testing
PDF
Testing Web Apps with Spring Framework 3.2
PDF
WordPress Acceptance Testing, Solved!
PDF
Testing for fun in production Into The Box 2018
PPTX
Visual Studio 2010 for testers
PDF
WinAppDriver - Windows Store Apps Test Automation
PDF
Spring 3 - Der dritte Frühling
PPTX
Rapid prototyping of eclipse rcp applications - Eclipsecon Europe 2017
ODP
Getting to Grips with SilverStripe Testing
PDF
The what, why and how of web analytics testing
PPTX
QASymphony Atlanta Customer User Group Fall 2017
PDF
Spring 3 - An Introduction
PPTX
Bridging the communication Gap & Continuous Delivery
PPTX
1,2,3 … Testing : Is this thing on(line)? with Mike Martin
PPS
About Qtp_1 92
PPS
About QTP 9.2
PPS
About Qtp 92
PPT
QTP Online Training
Serverless Apps with AWS Step Functions
Continuous Delivery: How RightScale Releases Weekly
Netserv Software Testing
Testing Web Apps with Spring Framework 3.2
WordPress Acceptance Testing, Solved!
Testing for fun in production Into The Box 2018
Visual Studio 2010 for testers
WinAppDriver - Windows Store Apps Test Automation
Spring 3 - Der dritte Frühling
Rapid prototyping of eclipse rcp applications - Eclipsecon Europe 2017
Getting to Grips with SilverStripe Testing
The what, why and how of web analytics testing
QASymphony Atlanta Customer User Group Fall 2017
Spring 3 - An Introduction
Bridging the communication Gap & Continuous Delivery
1,2,3 … Testing : Is this thing on(line)? with Mike Martin
About Qtp_1 92
About QTP 9.2
About Qtp 92
QTP Online Training

Recently uploaded (20)

PPTX
MYSQL Presentation for SQL database connectivity
PPTX
A Presentation on Artificial Intelligence
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
DOCX
The AUB Centre for AI in Media Proposal.docx
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
NewMind AI Weekly Chronicles - August'25-Week II
PPTX
Big Data Technologies - Introduction.pptx
PPTX
sap open course for s4hana steps from ECC to s4
PDF
Electronic commerce courselecture one. Pdf
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PPTX
Programs and apps: productivity, graphics, security and other tools
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Machine learning based COVID-19 study performance prediction
PDF
A comparative analysis of optical character recognition models for extracting...
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
MYSQL Presentation for SQL database connectivity
A Presentation on Artificial Intelligence
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Diabetes mellitus diagnosis method based random forest with bat algorithm
The AUB Centre for AI in Media Proposal.docx
Digital-Transformation-Roadmap-for-Companies.pptx
NewMind AI Weekly Chronicles - August'25-Week II
Big Data Technologies - Introduction.pptx
sap open course for s4hana steps from ECC to s4
Electronic commerce courselecture one. Pdf
MIND Revenue Release Quarter 2 2025 Press Release
Programs and apps: productivity, graphics, security and other tools
20250228 LYD VKU AI Blended-Learning.pptx
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Dropbox Q2 2025 Financial Results & Investor Presentation
Machine learning based COVID-19 study performance prediction
A comparative analysis of optical character recognition models for extracting...
gpt5_lecture_notes_comprehensive_20250812015547.pdf
The Rise and Fall of 3GPP – Time for a Sabbatical?
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx

GeeCON 2014 - Spring Testing