SlideShare une entreprise Scribd 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/

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

Structuring Teams and Portfolios for Success
Structuring Teams and Portfolios for SuccessStructuring Teams and Portfolios for Success
Structuring Teams and Portfolios for Success
UXDXConf
 

Dernier (20)

Intro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджераIntro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджера
 
A Business-Centric Approach to Design System Strategy
A Business-Centric Approach to Design System StrategyA Business-Centric Approach to Design System Strategy
A Business-Centric Approach to Design System Strategy
 
10 Differences between Sales Cloud and CPQ, Blanka Doktorová
10 Differences between Sales Cloud and CPQ, Blanka Doktorová10 Differences between Sales Cloud and CPQ, Blanka Doktorová
10 Differences between Sales Cloud and CPQ, Blanka Doktorová
 
Structuring Teams and Portfolios for Success
Structuring Teams and Portfolios for SuccessStructuring Teams and Portfolios for Success
Structuring Teams and Portfolios for Success
 
What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024
 
Speed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in MinutesSpeed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in Minutes
 
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
 
Syngulon - Selection technology May 2024.pdf
Syngulon - Selection technology May 2024.pdfSyngulon - Selection technology May 2024.pdf
Syngulon - Selection technology May 2024.pdf
 
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdfIntroduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
 
Optimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through ObservabilityOptimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through Observability
 
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdfSimplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
 
ECS 2024 Teams Premium - Pretty Secure
ECS 2024   Teams Premium - Pretty SecureECS 2024   Teams Premium - Pretty Secure
ECS 2024 Teams Premium - Pretty Secure
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
 
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdfHow Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
 
Powerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara LaskowskaPowerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara Laskowska
 
AI revolution and Salesforce, Jiří Karpíšek
AI revolution and Salesforce, Jiří KarpíšekAI revolution and Salesforce, Jiří Karpíšek
AI revolution and Salesforce, Jiří Karpíšek
 
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
 
UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1
 
IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024
 
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
 

Software Passion Summit 2012 - Testing of Spring