SlideShare une entreprise Scribd logo
1  sur  51
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/

Contenu connexe

En vedette

Suku kata kvk
Suku kata kvkSuku kata kvk
Suku kata kvk
Solar Yee
 

En vedette (15)

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

Similaire à Software Passion Summit 2012 - Testing of Spring

Unit test candidate solutions
Unit test candidate solutionsUnit test candidate solutions
Unit test candidate solutions
benewu
 
Spring 3: What's New
Spring 3: What's NewSpring 3: What's New
Spring 3: What's New
Ted Pennings
 
Testing Web Apps with Spring Framework 3.2
Testing Web Apps with Spring Framework 3.2Testing Web Apps with Spring Framework 3.2
Testing Web Apps with Spring Framework 3.2
Sam Brannen
 
Test strategy for web development
Test strategy for web developmentTest strategy for web development
Test strategy for web development
alice yang
 
Qtp Training
Qtp TrainingQtp Training
Qtp Training
mehramit
 
Qtp Presentation
Qtp PresentationQtp Presentation
Qtp Presentation
techgajanan
 

Similaire à Software Passion Summit 2012 - Testing of Spring (20)

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

Dernier

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Dernier (20)

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 

Software Passion Summit 2012 - Testing of Spring