SlideShare a Scribd company logo
Testing of Spring
Mattias Severson
Mattias
http://blog.jayway.com/
Agenda
• Basic Spring Testing
• Embedded Database
• Transactions
• Profiles
• Controller Test
Bank App
AccountRepository AccountEntity
AccountRepository
AccountService
AccountEntity
ImmutableAccount
AccountRepository
AccountService
BankController
AccountEntity
ImmutableAccount
Basics
jUnit test
public class ExampleTest {
Example example;
@Before
public void setUp() {
example = new ExampleImpl();
}
@Test
public void testDoSomething() {
example.doSomething();
// verify ...
}
}
@Autowired
public class ExampleTest {
@Autowired
Example example;
@Test
public void testDoSomething() {
example.doSomething();
// verify ...
}
}
@ContextConfiguration
@ContextConfiguration("/application-context.xml")
public class ExampleTest {
@Autowired
Example example;
@Test
public void testDoSomething() {
example.doSomething();
// verify ...
}
}
public class ExampleTest {
@Autowired
Example example;
@Test
public void testDoSomething() {
example.doSomething();
// verify ...
}
}
@ContextConfiguration
@ContextConfiguration("classes=TestConfig.class")
public class ExampleTest {
@Autowired
Example example;
@Test
public void testDoSomething() {
example.doSomething();
// verify ...
}
}
@ContextConfiguration
@ContextConfiguration("/application-context.xml")
public class ExampleTest {
@Autowired
Example example;
@Test
public void testDoSomething() {
example.doSomething();
// verify ...
}
}
SpringJUnit4ClassRunner
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/application-context.xml")
public class ExampleTest {
@Autowired
Example example;
@Test
public void testDoSomething() {
example.doSomething();
// verify ...
}
}
@ContextConfiguration("/application-context.xml")
public class ExampleTest {
@Autowired
Example example;
@Test
public void testDoSomething() {
example.doSomething();
// verify ...
}
}
@ContextConfiguration
• Caches ApplicationContext
• unique context configuration
• within the same test suite
• All tests execute in the same JVM
@ContextConfiguration
• @Before / @After
• Mockito.reset(mockObject)
• EasyMock.reset(mockObject)
• @DirtiesContext
Embedded DB
AccountRepository AccountEntity
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
Java Config
@Configuration
public class EmbeddedDbConfig {
@Bean
public DataSource dataSource() {
return new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.HSQL)
.addScript(“classpath:db-schema.sql”)
.addScript(“classpath:db-test-data.sql”)
.build();
}
}
Transactions
Tx Test
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/application-context.xml")
public class ExampleTest {
@Test
public void testDoSomething() {
// call DB
}
}
@Transactional
@Test
public void testDoSomething() {
// call DB
}
Tx Annotations
@TransactionConfiguration
@BeforeTransaction
@AfterTransaction
@Rollback
Demo
Spring Profiles
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>
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”)
Tests and Profiles
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(“/application-context.xml”)
public class SomeTest {
@Autowired
SomeClass someClass;
@Test
public void testSomething() { ... }
}
@ActiveProfiles("testProfile")
Demo
AccountRepository
AccountService
AccountEntity
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("...");
<beans profile="default">
<!-- Default beans -->
</beans>
System.getProperty("spring.profiles.default");
Test Controller
AccountRepository
AccountService
BankController
AccountEntity
ImmutableAccount
Demo
spring-test-mvc
XML config
MockMvc mockMvc = MockMvcBuilders
.xmlConfigSetup("classpath:appContext.xml")
.activateProfiles(...)
.configureWebAppRootDir(warDir, false)
.build();
Java config
MockMvc mockMvc = MockMvcBuilders
.annotationConfigSetup(WebConfig.class)
.activateProfiles(...)
.configureWebAppRootDir(warDir, false)
.build();
Manual config
MockMvc mockMvc = MockMvcBuilders
.standaloneSetup(new BankController())
.setMessageConverters(...)
.setValidator(...)
.setConversionService(...)
.addInterceptors(...)
.setViewResolver(...)
.setLocaleResolver(...)
.build();
Test
mockMvc.perform(get("/")
.accept(MediaType.APPLICATION_JSON))
.andExpect(response().status().isOk())
.andExpect(response().contentType(MediaType))
.andExpect(response().content().xpath(String).exists())
.andExpect(response().redirectedUrl(String))
.andExpect(model().hasAttributes(String...));
Demo
Integration tests
jetty-maven-plugin
<executions>
<execution>
<id>start-jetty</id>
<phase>pre-integration-test</phase>
<goals>
<goal>run</goal>
</goals>
</execution>
<execution>
<id>stop-jetty</id>
<phase>post-integration-test</phase>
<goals>
<goal>stop</goal>
</goals>
</execution>
</executions>
maven-failsafe-plugin
IT*.java
*IT.java
*ITCase.java
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");
}
Conclusions
• Basic Spring Testing
• Embedded database
• Transactions
• Profiles
• Controller Test
Questions?
http://blog.jayway.com/

More Related Content

PDF
GeeCON 2014 - Spring Testing
PPT
Qtp 9.2 tutorials
PPTX
OmniFaces validators
PPT
Mastering OmniFaces - A Problem to Solution Approach
PPTX
Controllers & actions
PPTX
Refactoring Legacy Web Forms for Test Automation
PPTX
Automation Testing with TestComplete
PPTX
Spring framework part 2
GeeCON 2014 - Spring Testing
Qtp 9.2 tutorials
OmniFaces validators
Mastering OmniFaces - A Problem to Solution Approach
Controllers & actions
Refactoring Legacy Web Forms for Test Automation
Automation Testing with TestComplete
Spring framework part 2

Viewers also liked (15)

PDF
projeto_escola_alimenta
PPT
The RSS Revolution: Using Blogs and Podcasts to Distribute Learning Centent
PPT
“Change the game for tigers”
PPT
Big Data and Next Generation Mental Health
PDF
LSA-ing Wikipedia with Apache Spark
PPS
Human Alphabets 3 (new)
PDF
Agile - Community of Practice
PPS
Pilobolus Dance Theater
PDF
Practical Test Strategy Using Heuristics
PDF
#MayoInOz Opening Keynote
PPTX
Pólipos uterinos: endometriales y endocervicales
PPTX
Patología endometrial
PPT
Suku kata kvk
PPSX
Dimitar Voinov Art
PPTX
Streebo Manufacturing Apps Suite
projeto_escola_alimenta
The RSS Revolution: Using Blogs and Podcasts to Distribute Learning Centent
“Change the game for tigers”
Big Data and Next Generation Mental Health
LSA-ing Wikipedia with Apache Spark
Human Alphabets 3 (new)
Agile - Community of Practice
Pilobolus Dance Theater
Practical Test Strategy Using Heuristics
#MayoInOz Opening Keynote
Pólipos uterinos: endometriales y endocervicales
Patología endometrial
Suku kata kvk
Dimitar Voinov Art
Streebo Manufacturing Apps Suite
Ad

Similar to Software Passion Summit 2012 - Testing of Spring (20)

PDF
SpringOne 2GX 2013 - Spring Testing
PDF
WordPress Acceptance Testing, Solved!
PPTX
Apex Testing and Best Practices
PPTX
Unit test candidate solutions
PPTX
Dependency injection - the right way
PDF
Spring 3: What's New
PDF
Testing Web Apps with Spring Framework 3.2
PPT
Test strategy for web development
ODP
Mastering Mock Objects - Advanced Unit Testing for Java
PDF
Test Pyramid in Microservices Context
PPT
Qtp Training
PDF
Spring 3.1 and MVC Testing Support
PPT
QTP Online Training
PDF
Testing for fun in production Into The Box 2018
PPTX
Rapid prototyping of eclipse rcp applications - Eclipsecon Europe 2017
PDF
We Are All Testers Now: The Testing Pyramid and Front-End Development
PPT
Qtp Presentation
PDF
Unit testing 101
PPTX
Testing ASP.NET - Progressive.NET
PPTX
Clean tests good tests
SpringOne 2GX 2013 - Spring Testing
WordPress Acceptance Testing, Solved!
Apex Testing and Best Practices
Unit test candidate solutions
Dependency injection - the right way
Spring 3: What's New
Testing Web Apps with Spring Framework 3.2
Test strategy for web development
Mastering Mock Objects - Advanced Unit Testing for Java
Test Pyramid in Microservices Context
Qtp Training
Spring 3.1 and MVC Testing Support
QTP Online Training
Testing for fun in production Into The Box 2018
Rapid prototyping of eclipse rcp applications - Eclipsecon Europe 2017
We Are All Testers Now: The Testing Pyramid and Front-End Development
Qtp Presentation
Unit testing 101
Testing ASP.NET - Progressive.NET
Clean tests good tests
Ad

Recently uploaded (20)

PDF
cuic standard and advanced reporting.pdf
PDF
Network Security Unit 5.pdf for BCA BBA.
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PPTX
Spectroscopy.pptx food analysis technology
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
DOCX
The AUB Centre for AI in Media Proposal.docx
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
A comparative analysis of optical character recognition models for extracting...
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Electronic commerce courselecture one. Pdf
cuic standard and advanced reporting.pdf
Network Security Unit 5.pdf for BCA BBA.
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Reach Out and Touch Someone: Haptics and Empathic Computing
Programs and apps: productivity, graphics, security and other tools
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
gpt5_lecture_notes_comprehensive_20250812015547.pdf
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Spectroscopy.pptx food analysis technology
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
The AUB Centre for AI in Media Proposal.docx
Digital-Transformation-Roadmap-for-Companies.pptx
MIND Revenue Release Quarter 2 2025 Press Release
A comparative analysis of optical character recognition models for extracting...
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Chapter 3 Spatial Domain Image Processing.pdf
Assigned Numbers - 2025 - Bluetooth® Document
Dropbox Q2 2025 Financial Results & Investor Presentation
Electronic commerce courselecture one. Pdf

Software Passion Summit 2012 - Testing of Spring